您好,感谢您的帮助
当我写一些代码时遇到了一个问题。在下面的例子中。我期待 alert(a.x)
输出 1,而不是它输出 2。我了解到这是因为 a
被传递给 this。 b
作为引用。我似乎找不到的是如何按值(value)传递它。 (例如,我不想每次调用 x()
时都修改 a
)
var a = {"x":1}
function x() {
this.b = v;
this.b.x++;
}
x();
alert(a.x); //prints 2
我也尝试了以下和其他变体无济于事...
var a = {"x":1}
function x(v) {
this.b = v;
this.b.x++;
}
x(a);
alert(a.x); //... still prints 2
谁能告诉我我缺少什么?
谢谢你
(旁注:this is a post 接近我正在谈论的内容,但我无法弄清楚如何使其适用于我的情况......如果情况完全相同)
因此,也许我可以通过分解正在发生的事情来为您提供一些清晰度。
var a = {"x":1} // a refers to object with key "x"
function x(v) { // v is now a reference to the object with key "x"
this.b = v; // this.b now is a reference to the object with key "x"
this.b.x++; //this.b.x++ points to the object with key "x" so it can increment it's value.
}
x(a); // passes in a the value of reference to object with key "x"
alert(a.x); //... still prints 2
您可以做一些可以在 this 中找到的事情链接:
var o = {};
(function(x){
var obj = Object.create( x );
obj.foo = 'foo';
obj.bar = 'bar';
})(o);
alert( o.foo ); // undefined