【问题标题】:Access JavaScript "this" from TypeScript从 TypeScript 访问 JavaScript “this”
【发布时间】:2015-12-18 23:31:26
【问题描述】:

我目前正在我的 typescript 项目中使用 AlpacaJS 库。这个 JavaScript/JQuery 库包含在我的 Typescript 类中,并希望我在 json 样式对象中传递一些选项,如下所示:

this.options = {
    "collapsible": false,
    "fields": {
        "id": {
            "events": {
                "change": function () {
                    console.log(this.getValue());
                }
            }
        }
    }
};

传递这个对象我说:在 alpaca 生成的表单中的“id”字段中添加一个更改事件。在该函数中使用“this”给了我库的“this”,而不是 typescript 类“this”。

问题:如果我想在我的 Typescript 类中调用方法或变量怎么办?我必须使用“this”,但“this”绑定到 alpaca/javascript this。我无法将其更改为(event) => { ... }{ ...}.bind(this),因为这样我可以访问打字稿“this”,但我无法访问 alpaca/javascript 这个,我需要它们两个....

【问题讨论】:

    标签: javascript typescript this alpacajs


    【解决方案1】:

    我无法访问 alpaca/javascript 这个,我需要它们两个

    在创建函数之前使用捕获this的标准javascript技巧:

    let _self = this;
    this.options = {
        "collapsible": false,
        "fields": {
            "id": {
                "events": {
                    "change": function () {
                        console.log(_self.getValue());  // the class instance
                        console.log(this); // the lib version 
                    }
                }
            }
        }
    };
    

    这里也记录了这个提示:https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

    【讨论】:

    • 使用self withtin typescript 返回Window 类型的对象?它不包含我的 Typescript 方法/变量
    • 我错过了let _self = this; -.- 对不起。看起来这很有效!去测试一下
    • 之间,只是想知道。为什么我可以在这个块范围内访问let,但我不能访问其他打字稿变量/函数?
    • can't i access the other typescript variables/functions? :可以。不知道你的意思
    • So why can't i, but can i access the _self 实际上是一个变量 this 只能绑定一件事。如果您使用粗箭头,则它绑定到词法范围(在您的情况下为类实例)。没有它,它是 谁调用函数(在这种情况下是库)的选择。因为你想要两件事,你需要使用两个变量。在您的情况下,一个是this(来自lib),另一个是_self(绑定到类实例)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 2016-07-15
    • 2016-05-17
    • 2017-09-06
    • 2021-01-05
    相关资源
    最近更新 更多