Typescript:将函数作为参数传递返回window对象而不是构造函数对象

时间:2018-02-05 12:12:14

标签: javascript typescript arguments

我对typescript很新,所以我有这个函数在Class构造函数中调用另一个函数,但是在sayHelloAgain()里面调用this时返回窗口对象

Greeter.init()我正在呼叫this.sayHello("message string", parameterCallback)

中的

class Greeter {
    init() { 
        this.sayHello("hello", this.sayHelloAgain);
    }
    sayHello(msg, callbackFunction) {
        // Return Greeter object
        console.log(this);
        callbackFunction(msg);
    }
    sayHelloAgain(msg) {
        // Returns Window object instead of Greeter
        console.log(this)
    }
}

let greeter = new Greeter("world");

enter image description here

1 个答案:

答案 0 :(得分:3)

this是上下文的。在sayHelloAgain回调内,this关键字不再代表您班级的实例。

您可以通过以下方式避免这种情况:

1 - 使用.bind(this)

this.sayHello("hello", this.sayHelloAgain.bind(this));

2 - 或创建另一个调用回调的函数:

this.sayHello("hello", (msg) => this.sayHelloAgain(msg));

3 - 或在回调中使用箭头功能

this.sayHello("hello", this.sayHelloAgain);
sayHelloAgain = (msg) => { /* ... */ }
相关问题