首页 > 解决方案 > 在打字稿中进行封闭的最佳方法

问题描述

请检查下面的代码,我想增加计数并根据我想更改打字稿(角度)中的 backgroundColor 变量的计数。问题是当 changeColor() 函数被调用时,计数不增加并且 backgroundColor 显示未定义。

export class AppComponent {
  title = "angularExample";
  backgroundColor = "yellow";

  changeColor() {
    let count = 0;
    function displayNumber() {
      alert(++count + this.backgroundColor);
    }
    displayNumber();
  }
}

标签: angulartypescript

解决方案


您应该为此使用箭头函数,因为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);
}

推荐阅读