Why does console.log () not take a snapshot of past variables?

I came across some really weird behavior with javascript today. I think I somehow understood this, but I would like to know if what I think is really happening is happening, or if there is any other magic. 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: ab, top: ba}; }; SomeObject.magicalStuff = function(position) { position.left = 0; }; SomeObject.foo(100, 50); 

Code in jsFiddle

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

 > Object 50 

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

 > Object left: 0 top: -50 

While I would expect:

 > Object left: 50 top: -50 

What I think is that console.log () really just "sends" a link to the console, which is read after clicking on the "expand" symbol. But isn't console.log () target hitting as a debugging tool? I always expected console.log () to strip the stuff that I pass to it. Actually, it’s amazing to see a statement that arises after the actual console.log () changes the output of this very call to console.log ().

Or is there something else?

Edit: I am also wondering if there is a reasonable reason for browser developers to implement console.log like this (I think there is one, otherwise it will not be consistent in the main browsers).

+18
javascript debugging console
Mar 07 '11 at 18:20
source share
3 answers

Firebug has console.dir() for what you want.

In general, it is not possible to print each level of nested properties, because objects can contain circular references, such as var a = {}; var b = {a: a}; ab = b; var a = {}; var b = {a: a}; ab = b;

Implementing the ideal clone method is very complex - I think it would just dump all the memory, and the record would be terribly long. Think about console.log(window) ...

+10
Mar 07 2018-11-23T00:
source share

Yes, this is what happens. I would suggest that this is done to minimize the overhead of calling console.log() . Things can get out of hand if each object has been deeply cloned for each call to the log.

When I need to get around this, I either JSON.stringify() or the small clones the object before passing it to console.log() .

+9
Mar 07 2018-11-18T00:
source share

I also saw this behavior, and it is sure that the link is published. To get around this, I used the clone () method in jQuery about what I wanted to register.

+6
Mar 07 '11 at 18:25
source share



All Articles