Javascript绑定与其实例一起工作



让我们取一个对象

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

在第二段代码中,op相同的对象

p.ao.a指的是同一个值:

var o = {x: 5, f: function() {return this.x;}};
var p = o;
o.x = 10;
console.log(p.x) // 10

第二段代码的结果与thisbind无关。


.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())或闭包可能是您正在寻找的。

最新更新