如何在 JS 对象初始化中使用 bind()

How to use bind() in JS object init

全部:

我想知道我是否想将 this 绑定到一个对象函数,我该怎么做?喜欢:

var a  = {
    name:"nihao", 
    hello: (function(){
        console.log(this.name);
    }).bind(this)
}

当我运行a.hello()时,这个就是Window。然后我将代码更改为:

var a  = {
    name:"nihao", 
    hello: (function(){
        console.log(this.name);
    }).bind(a)
}

什么都没有改变,所以我想知道在初始化这个对象时如何绑定 a?

谢谢

在这种情况下,您需要稍后绑定函数;一旦 "a" 被初始化。

a.hello = (function hello(){}).bind(a);

首先,不要在对象定义中添加绑定:

var a  = {
  name: "nihao", 
  hello: function(){
    console.log(this.name);
  }
}

然后,在调用过程中,传递任何你想成为的对象this:

a.hello.call(a);
// => "nihao"

a.hello.call({name: "Kuan"});
// => "Kuan"

为什么不呢?

var a  = {
    name:"nihao", 
    hello: function(){
        console.log(this.name);
    }
}

a.hello();

默认情况下,对象内的函数 属性 绑定到该实例。