让我们取一个对象
var o = {a : 10 ,b:20,f:function(){ return this.a + this.b; }};
console.log(o.f())//30 works as expected
现在var o = {a:10,b:20,f:function(){ return this.a + this.b; }};
var p = o;
p.a = 1;
p.b = 4;
console.log(p.f()); // 5 works fine
console.log(o.f()); //5,it should 30 right but why it is showing 5
为什么它是这样工作的。如果我执行o.f()
,它应该从对象o
中获取值。
看起来我没有正确理解绑定
console.log(o.f.bind(o)())//gives 5
console.log(o.f.bind(this)())//gives 30
请给出这两行代码的差值
您正在将object
引用分配给另一个变量,而不是副本。
var o = {a:10,b:20,f:function(){ return this.a + this.b; }};
var p = o; //Assigning the reference of o to p.
因此,它的行为是这样的,这就是语言的工作方式。
关于你的第二个问题,
console.log(o.f.bind(o)()); // 5
这根本没有任何效果。您根本没有改变该函数的this
值。
console.log(o.f.bind(this)()); // NaN
将该函数的this
值更改为正在执行bind
的上下文的this
值。例如,如果你在window的上下文中执行它,this
将是window
, window.a
将是undefined
, window.b
也将是undefined
。所以undefined + undefined
将返回NaN
。不是你说的30
在第二段代码中,o
和p
是相同的对象。
即p.a
和o.a
指的是同一个值:
var o = {x: 5, f: function() {return this.x;}};
var p = o;
o.x = 10;
console.log(p.x) // 10
第二段代码的结果与this
或bind
无关。
.bind(newObject)
创建一个新函数,将this
的值"修改"为指定的newObject
。(旁白:在方法之外使用this
通常没有意义,因为它将被定义为window
[它也包含所有全局变量]。)
例如,考虑这些对象:
var u = {x: 5, f: function() {return this.x;}};
var v = {x: 20};
如果你想把这个方法从u
"复制"到v
,你可以这样做:
v.f = u.f.bind(v);
console.log(u.f()) // 5 // .bind() doesn't change the old function
console.log(v.f()) // 20
p = o
复制引用,而不是创建新对象。使用构造函数(原型中有f()
)或闭包可能是您正在寻找的。