[英]Access JavaScript “this” from TypeScript
我目前正在使用我的打字稿项目中的AlpacaJS库。 这个JavaScript / JQuery库包含在我的Typescript类中,并希望我在json样式对象中传递一些选项,如下所示:
this.options = {
"collapsible": false,
"fields": {
"id": {
"events": {
"change": function () {
console.log(this.getValue());
}
}
}
}
};
通过这个对象,我说:将更改事件添加到羊驼生成的表单中的字段“id”。 在该函数中使用“this”给出了库的“this”,而不是typescript类“this”。
问题 :如果我想在我的Typescript类中调用方法或变量怎么办? 我将不得不使用“这个”,但“这个”绑定到羊驼/ javascript这个。 我无法将其更改为(event) => { ... }
或{ ...}.bind(this)
因为这样我可以访问打字稿“this”,但我无法访问羊驼/ javascript这个,我需要他们两个....
我不能访问羊驼/ 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.