DIV CSS 佈局教程網

JS 嵌套函數中的 this 指向問題與解法
編輯:JavaScript綜合知識     

「在外層函數裡 this 指向正確,一進到內層函數就變了」是 JavaScript 面試與實務的常見陷阱。原因在於 this 的值取決於「函數怎麼被呼叫」,而不是「函數寫在哪裡」。

問題重現

var stu = {
  m: function () {
    var self = this;
    console.log(this === stu);        // ==> true

    function f() {
      // 直接呼叫 f() 時,this 不再指向外層的 stu
      console.log(this === stu);      // ==> false
      console.log(self === stu);      // ==> true
    }
    f();
  }
};
stu.m();

stu.m() 是「以 stu 為接收者呼叫」,所以 this 是 stu。但 f() 是「單純呼叫一個函數」,在非嚴格模式下 this 會落到全域物件(window),嚴格模式下則是 undefined。它不會自動繼承外層的 this。

解法一:把 this 存進變數(self / that)

這是最經典的做法,也就是上面程式碼裡的 self:

var stu = {
  name: '小明',
  m: function () {
    var self = this;                 // 先把 this 存起來
    setTimeout(function () {
      console.log(self.name);        // 小明
    }, 100);
  }
};
stu.m();

閉包會保留 self 這個變數的引用,所以即使 m 已執行完,內層仍能取到正確的值。

解法二:用 call / apply / bind 明確指定

var stu = {
  name: '小明',
  m: function () {
    function f() {
      console.log(this.name);
    }
    f.call(this);        // 明確把外層的 this 傳進去
    // 或 f.apply(this);
  }
};
stu.m();

若要傳給回呼函式,用 bind 產生一個綁好 this 的新函數:

var stu = {
  name: '小明',
  m: function () {
    function f() { console.log(this.name); }
    setTimeout(f.bind(this), 100);
  }
};
stu.m();

解法三:箭頭函數(ES2015+)

箭頭函數沒有自己的 this,它會直接沿用定義所在外層作用域的 this,這正是我們想要的行為:

var stu = {
  name: '小明',
  m: function () {
    setTimeout(() => {
      console.log(this.name);        // 小明,this 繼承自 m
    }, 100);
  }
};
stu.m();

但要注意:箭頭函數不能拿來當物件方法或建構子,因為它的 this 是被繼承而非被指定。

// 反例:箭頭函數當方法,this 不會是 obj
var obj = {
  name: '小明',
  m: () => console.log(this.name)   // undefined
};
obj.m();

this 的優先順序速查

  1. new 呼叫:this 是新建立的物件。
  2. call/apply/bind:this 是明確指定的值。
  3. 以「物件.方法()」呼叫:this 是該物件。
  4. 一般函數呼叫:嚴格模式為 undefined,非嚴格模式為全域物件。
  5. 箭頭函數:一律繼承外層作用域的 this,以上規則都不適用。

記住順序,绝大多数 this 的疑惑都能立刻釐清。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved