【问题标题】:How to properly do a "bind" in angular2 typescript?如何在 angular2 typescript 中正确地进行“绑定”?
【发布时间】:2017-12-21 13:04:36
【问题描述】:

我想使用一个需要像这样创建对象并绑定到它的 javascript 库:

this.mystr = "hello";
this.webkitspeech = new webkitSpeechRecognition();
this.webkitspeech.onresult = function(evt) {
    console.log(this.mystr); // this is undefined, even though I do have it defined
}

我通常会做一个.bind(this)

虽然在打字稿中我想这样做:

this.mystr = "hello"
this.webkitspeech = new webkitSpeechRecognition();
this.webkitspeech.onresult = onresult;

onresult(event) {    
    console.log(this.mystr) // this is undefined, even though I do have it defined
}

.bind(this) 在此示例中不起作用。我该如何解决这个问题?除了.bind(this),还有其他选择吗?或者任何适用于打字稿功能的东西?

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    在 TypeScript 和 ES6 中,绑定函数最方便的方法是使用 arrow function 保留上下文:

    this.webkitspeech.onresult = ($event) => { this.onresult($event) };
    

    或者像这样使用bind

    this.webkitspeech.onresult = this.onresult.bind(this);
    

    或者你可以像这样使用TS实例箭头函数(ES类属性):

    class MyClass() {
       onresult = ($event) => {...}
       ...
       this.webkitspeech.onresult = onresult;
    }
    

    类属性是 stage 2 ES7 proposal,目前 TS 支持。

    See the documentation 用于方法之间的一些比较。

    【讨论】:

    • @yurzui,谢谢,这也是我提到的 3 种方法。我已将参考放入答案中
    • 如何获取 this.mystr 的引用呢?会被定义还是未定义?
    • @Rolando, this 将指向类实例,因此您将可以访问所有 class 成员,包括 mystr
    猜你喜欢
    • 2016-11-25
    • 2017-02-05
    • 1970-01-01
    • 2017-08-23
    • 2016-11-17
    • 2022-09-29
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多