【问题标题】:Why is this property showing up undefined in angular?为什么这个属性在角度中显示为未定义?
【发布时间】:2021-11-18 03:34:45
【问题描述】:

我似乎无法弄清楚为什么第一个 console.log 正确显示参数但第二个显示未定义。

控制台日志输出:

text
undefined

代码:

ngOnInit() {
this.getPuzzle();
}
    getPuzzle() {
    this.restProviderService.getPuzzle(this.gameService.getGameId()).subscribe(puzzle => {
      this.puzzleType = puzzle.type;
      this.puzzleValue = puzzle.value;

      console.log(this.puzzleType);

      setTimeout(this.handlePuzzle , 3000);
    });
  }
    
      handlePuzzle() {
          console.log(this.puzzleType);
          if (this.puzzleType == 'text') {
            new Vara("#text", "assets/fonts/vara/Satisfy/SatisfySL.json", [{
              text: 'hello',
              delay: 2000,
              x: 2
            }], {
              fontSize: 25,
              strokeWidth: 1.5,
              duration: 5000,
              color: "black"
            });
          }
        
    
      }

【问题讨论】:

    标签: javascript angular typescript ionic-framework rxjs


    【解决方案1】:

    当您将函数this.handlePuzzle 传递给setTimeout 时,代表您的类的this 会丢失,而handlePuzzle 会收到setTimeoutthis

    使用箭头函数而不是传递函数本身:

    setTimeout(() => this.handlePuzzle(), 3000);
    

    【讨论】:

      【解决方案2】:

      JS 事件监听器内部this 指的是事件目标。 但是在handlePuzzle 方法(某种事件监听器)内部,您需要this 来引用当前对象实例(就像在方法中一样)。

      您有 2 个解决方案:

      • 使用箭头回调。箭头回调保留 this 的值。

        setTimeout(()=>this.handlePuzzle(), 3000)

        或者在你的方法声明中

        handlePuzzle=()=> { console.log(this.puzzleType);

      • 使用bind设置this的值。

        setTimeout(this.handlePuzzle.bind(this), 3000);

        或者,在构造函数中

        this.handlePuzzle = this.handlePuzzle.bind(this);

      有关详细信息,请参阅以下文章。 https://dev.to/alexdevero/a-quick-guide-to-this-keyword-in-javascript-what-this-is-and-when-7i5

      【讨论】:

        猜你喜欢
        • 2020-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-08
        • 2012-07-02
        • 2017-02-12
        • 2022-01-14
        • 1970-01-01
        相关资源
        最近更新 更多