使用bind来确保方法引用对象,但它似乎不起作用

mik*_*ana 1 javascript oop methods bind

在我正确的Javascript中进行实验,我试图从另一个方法(WaitAndSayHello)运行一个方法(SayHello).由于涉及回调,我使用bind来确保每个方法中的'this'引用该对象.

pretendThingConstructor = function (greeting) {
    this.greeting = greeting;

    this.SayHello = function() {
        console.log(this.greeting); // Works
    };

    this.WaitAndSayHello = function() {
        setTimeout(function() { 
            console.log(this)  
            this.SayHello() // Fails
        }, 500);
    }
    this.WaitAndSayHello.bind(this); // This bind() doesn't seem to work
}


var pretend_thing = new pretendThingConstructor('hello world');
pretend_thing.SayHello();
pretend_thing.WaitAndSayHello();
Run Code Online (Sandbox Code Playgroud)

代码打印'hello world',然后第二次'对象#没有方法'SayHello'失败.我可以从console.log中看到'this'指的是事件.但是不应该使用bind()修复此问题?

如何使bind()工作?

另外,我想干净利落地做到这一点:即,不要在多个地方引用对象的名称.

jAn*_*ndy 5

你不能"迟到" .bind().你需要在函数声明时调用它,比如

this.WaitAndSayHello = function() {
    setTimeout(function() { 
        console.log(this)  
        this.SayHello() // Fails
    }, 500);
}.bind(this)
Run Code Online (Sandbox Code Playgroud)

此外,您传入的匿名函数setTimeout()会创建一个新的上下文,因此具有自己的this上下文值.

您需要this在变量中保留对"外部" 的引用

this.WaitAndSayHello = function() {
    var self = this;

    setTimeout(function() { 
        console.log(self)  
        self.SayHello() // succeeds
    }, 500);
}.bind(this)
Run Code Online (Sandbox Code Playgroud)

或者.bind()再次使用,比如

this.WaitAndSayHello = function() {
    setTimeout(function() { 
        console.log(this)  
        this.SayHello() // succeeds
    }.bind(this), 500);
}.bind(this)
Run Code Online (Sandbox Code Playgroud)