Why doesn't console.log() take a snapshot of the passed variables?

I've ran into some really weird behavior with javascript today. I think I got it somehow figured out now, but I'd like to know if what I think is going on is really happening or if there is some other magic involved. So this is my code:

    var SomeObject = {};

    SomeObject.foo = function(a, b) {
       var baz = this.bar(a, b);
       console.log(baz);
       console.log(baz.left);
       SomeObject.magicalStuff(baz);
    };

    SomeObject.bar = function(a, b) {
        return {left: a-b, top: b-a};
    };

    SomeObject.magicalStuff = function(position) {
        position.left = 0;
    };

    SomeObject.foo(100, 50);

The code at jsFiddle

The output of this is something like (depending on the browser):

> Object
50

If you expand the "Object" (in Chrome, Safari or Firefox (Firebug) what you get is:

> Object
    left: 0
    top: -50

Whereas I would expect:

> Object
    left: 50
    top: -50

What I think is going on is that console.log() really just "posts" a reference to the console, which gets read once you click on the "expand" symbol. But doesn't that kind of defeat the purpose of console.log() as a debugging instrument? Я всегда ожидал, что console.log () сделает "снимок" того, что я ему передаю. Действительно удивительно видеть, что оператор, который идет после фактического console.log (), изменяет вывод этого самого вызова console.log ().

Или что-то еще происходит?

Edit: Мне также интересно, есть ли у разработчиков браузеров веская причина для реализации console.log таким образом (я полагаю, что она есть, иначе она не будет согласована в основных браузерах).

19
задан skaffman 7 March 2011 в 21:40
поделиться