angular - 在打字稿中进行封闭的最佳方法
问题描述
请检查下面的代码,我想增加计数并根据我想更改打字稿(角度)中的 backgroundColor 变量的计数。问题是当 changeColor() 函数被调用时,计数不增加并且 backgroundColor 显示未定义。
export class AppComponent {
title = "angularExample";
backgroundColor = "yellow";
changeColor() {
let count = 0;
function displayNumber() {
alert(++count + this.backgroundColor);
}
displayNumber();
}
}
解决方案
您应该为此使用箭头函数,因为this
不再是this
您期望的:
changeColor() {
let count = 0;
const displayNumber = () => {
alert(++count + this.backgroundColor);
};
displayNumber();
}
虽然,真的看不出你想做这样的事情的原因:)
最好只使用类字段:
export class AppComponent {
title = "angularExample";
backgroundColor = "yellow";
count = 0;
changeColor() {
this.displayNumber();
}
displayNumber() {
alert(++this.count + this.backgroundColor);
}
}
或者如果你真的想使用闭包(这是一个立即调用的函数表达式),我想你可以这样做:
export class AppComponent {
// ...
changeColor = ((count: number) => () => alert(++count + this.backgroundColor))(0);
}
推荐阅读
- python - 映射两个嵌套列表的排列
- javascript - 如何在 React 中动态更改组件的 className?
- vaadin - 鼠标滚轮上的 Vaadin 水平滚动
- arrays - 如何使 typedef'd 函数指针 extern
- python - 如何使用线程来加速我的功能?
- java - spring boot AbstractJPAConfiguration 未找到
- c# - Shell CurrentItem 使标签栏消失
- android - 当该函数需要在android中返回一个值时如何在线程中调用Room数据库函数
- angular - 角度路线:使用多个参数时的redirectTo
- node.js - Socket.io 或 Rest API