簡體   English   中英

JavaScript-具有傳遞函數的setInterval無法識別全局變量

[英]JavaScript - setInterval with passed function does not recognize global variables

我陷入了一個奇怪的問題,然后這個問題面臨一個挑戰,即要理解Angular為何會這樣,在Google上搜索該問題並沒有太多運氣 ,所以我在這里。

我想測試setInterval()函數並計數器一些變量,而不是太難了,而我陷入了無法找到解決方案或解釋的問題。

這是我正在使用的代碼,它可以正常工作:

public counter: number = 1;

  myFunction() {
    setInterval(() => {
      console.log(this.counter);
      this.counter++;
    }, 1000);
  }

Output: 1, 2, 3, 4, 5...

這段代碼可以正常工作,但是當我采用這樣的功能時,我未定義為輸出,然后是Nan, Nan, Nan

public counter: number = 1;

  foo() {
    console.log(this.counter);
    this.counter++;
  }

  myFunction() {
    setInterval(this.foo, 1000);
  }

* myFunction is the starting function *

Output: undefined, Nan, Nan, Nan...

我想變量訪問存在一些問題,即foo()無法訪問全局變量,但是這是怎么回事? 以及如何解決此問題?

這是您所描述的代碼

 class A{
 public counter: number = 1;

   foo() {
     alert(this.counter);
     this.counter++;
   }

   myFunction() {
     setInterval(this.foo, 1000);
   }
 }

 const a = new A();
 a.myFunction(); // output andefined, Nan, Nan ...

現在使用bind的代碼: JSFiddle

 class A{
 public counter: number = 1;

   foo() {
     alert(this.counter);
     this.counter++;
   }

   myFunction() {
     setInterval(this.foo.bind(this), 1000);
   }
 }

 const a = new A();
 a.myFunction(); // output 1, 2, 3, 4 ...

這是一個非常棘手的主題,所以

首先檢查此問題。 如何在回調中訪問正確的“ this”?

和情侶這個話題出奇好的答案在這里這里


現在綁定方法-Function.prototype.bind()

(來自文檔)

bind()方法創建一個新函數,該函數在被調用時將其關鍵字設置為提供的值,並在調用新函數時提供給定的參數序列。

並喜歡這種刪除方式(取自docs中的Examples部分):

bind()的最簡單用法是創建一個函數,無論該函數如何調用,都使用特定的this值進行調用。

新的JavaScript程序員一個常見的錯誤是從一個對象中提取的方法,然后在以后調用該函數,並期望它使用原來的對象作為this (例如,通過使用基於回調的代碼,方法)。 但是,如果沒有特別注意,原始對象通常會丟失。

使用原始對象從函數創建綁定函數可以很好地解決此問題

在第一個示例中,您傳遞了以es6簡寫形式聲明的函數(鏈接此處 ),因此, "this"將綁定到當前作用域。

在第二個示例中,您傳遞了對函數的引用,並且由於setTimeout在指向全局對象的情況下執行該函數,因此"this"等於窗口對象,因此屬性未定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM