我有这个变量:
public originalData: Array<any> = [];
这个函数:
canvas.onclick = function (evt) {
console.log(this.originalData);
}
该函数无法看到 this.originalData - 我如何在“onclick”方法中正确访问该变量和其他变量?我现在可以在函数之外执行此操作:
var dataCopy = this.originalData;
并通过“dataCopy”访问它,但是有没有一种方法可以访问变量而不创建新的 var 变量?
最佳答案
也许最好的方法是使用 the ES6 arrow function 。
An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target).
对于您的应用程序来说,它看起来像这样:
canvas.onclick = (evt) => {
console.log(this.originalData);
};
或者甚至:
canvas.onclick = e => console.log(this.originalData);
关于javascript - 在 TypeScript 函数内使用外部变量。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38443519/