javascript - Typescript:传递函数作为参数返回窗口对象而不是构造函数对象

标签 javascript typescript arguments

我对 typescript 还很陌生,所以我有这个函数,它调用类构造函数内的另一个函数,但是当调用 this 时sayHelloAgain() 内部返回窗口对象

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

最佳答案

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) => { /* ... */ }

关于javascript - Typescript:传递函数作为参数返回窗口对象而不是构造函数对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48622315/

相关文章:

javascript - 激活 meteor (turkserver)时应用程序崩溃

javascript - 检查单个字符是否为空格?

javascript - 如何共享变量并跟踪 Angular v4 ts 中多个组件的变化

javascript - typescript 中两个日期之间的天数列表

python - 更改子类中的默认构造函数参数值(从父类继承)

clojure - 如何将 "expand"列表作为函数的参数?

bash - 将变量当作参数来解析?

javascript - ReactJs,必须使用render吗

javascript - Jcrop 不适用于 ie 8

typescript - TS2345 : type 'Construct' is not a class derived from 'Construct'