this
变量在 Angular2 TypeScript 中的 js 方法或包之外无法访问。
public mousekeyAction() {
var mc=0,kc=0;
gkm.events.on('key.pressed', function (data) {
this.keyscount= kc++;
console.log(this.keyscount);
});
// Listen to all mouse events (click, pressed, released, moved, dragged)
gkm.events.on('mouse.*', function (data) {
this.mousecount=mc++;
console.log(this.mousecount);
});
}
最佳答案
您必须使用粗箭头
作为函数/回调而不是简单的函数。即使在函数之外,这也将维持 this 的范围。
像这样使用你的函数:-
public mousekeyAction() {
var mc=0,kc=0;
gkm.events.on('key.pressed', (data) => {
this.keyscount= kc++;
console.log(this.keyscount);
});
// Listen to all mouse events (click, pressed, released, moved, dragged)
gkm.events.on('mouse.*', (data) => {
this.mousecount=mc++;
console.log(this.mousecount);
});
}
有关更多信息,请参阅此处
关于javascript - `this` 变量在 Angular2 TypeScript 中的 js 方法或包之外无法访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42943397/