javascript - 在 TypeScript 函数内使用外部变量。

标签 javascript angularjs angular chart.js

我有这个变量:

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/

相关文章:

javascript - 在 ionic 2/3 中禁用 ionic 搜索栏

forms - Angular:实现嵌套表单的复合ControlValueAccessor

Angular 路由器 : named outlets does not seem to work with relative routes nor in lazy loaded modules

javascript - 每次点击后下拉关闭

javascript - 我可以从子组件到父组件获取计算数据吗?

javascript - 如何阻止数字变成负数

javascript - Angular 简单单页应用程序 - 未知提供商 : $routeProvider

angularjs - return 语句后无法访问代码 Angular Material 在 index.html 中链接时失败

angularjs - 将支付网关与 IONIC 集成

json - 从 heroku 获取有关 HTTPS 的错误