为什么console.log()不能获取传递的变量的快照? [英] Why doesn't console.log() take a snapshot of the passed variables?
问题描述
今天我遇到了一些很奇怪的行为与javascript。我想我现在已经弄清楚了,但我想知道我的想法是怎么回事真的发生,或者如果有一些其他的魔法参与。所以这是我的代码:
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 output of this is something like (depending on the browser):
> Object
50
如果展开对象(在Chrome,Safari或Firefox Firebug)你得到的是:
If you expand the "Object" (in Chrome, Safari or Firefox (Firebug) what you get is:
> Object
left: 0
top: -50
我会期望:
> Object
left: 50
top: -50
$ b b
我想的是,console.log()真的只是发布一个对控制台的引用,一旦你点击展开符号读取,但不是那样的失败console.log()作为调试工具的目的?
我总是期望console.log()来传递我传递给它的东西,看到一个在实际控制台之后的语句真令人惊讶。 log()改变console.log()调用的输出。
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? I always expected console.log() to "snapshot" the stuff I pass to it. It is really surprising to see a statement which comes after the actual console.log() change the output of that very console.log() call.
或者还有其他事情发生吗?
Or is there something else going on?
编辑:我也想知道浏览器开发者是否有正确的理由来实现这样的console.log(我想有一个,否则它不会在主要浏览器)。
I'm also wondering if there is a sound reason for browser developers to implement console.log like this (I guess there is one, otherwise it wouldn't be consistent across major browsers).
推荐答案
有 console.dir()
一般来说,每个级别的嵌套属性都不能打印,因为对象可以包含循环引用,例如 var a = {}; var b = {a:a}; ab = b;
实现完美的克隆
它将不得不基本上只是转储整个内存,并且日志将需要非常长。考虑 console.log(window)
...
Implementing a perfect clone
method is very hard - I guess it would have to basically just dump the whole memory, and logging would take awfully long. Think about console.log(window)
...
这篇关于为什么console.log()不能获取传递的变量的快照?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!