DIV CSS 佈局教程網

JavaScript this 的六種指向情境一次講清楚
編輯:JavaScript基礎知識     

this 是 JavaScript 面試與日常開發中最容易被誤解的概念之一。它的值並非在定義時決定,而是取決於「函數怎麼被呼叫」。以下整理六種常見情境。

一、以 new 呼叫時,this 指向新建立的實例

先看用與不用 new 的差別:

function Benjamin(username, sex) {
    this.username = username;
    this.sex = sex;
}
var benjamin = new Benjamin("zuojj", "male");
// Outputs: Benjamin {sex: "male", username: "zuojj"}
console.log(benjamin);

var ben = Benjamin("zhangsan", "female");
// Outputs: undefined
console.log(ben);

當建構函數被當成普通函數呼叫時,它沒有回傳值,而 this 會指向全域物件。要避免忘記寫 new 造成的問題,可以在函數內部做一次檢查:

function Benjamin(username, sex) {
  // Check whether "this" is a "Benjamin" object
  if (this instanceof Benjamin) {
      this.username = username;
      this.sex = sex;
  } else {
    return new Benjamin(username, sex);
  }
}

var benjamin = new Benjamin("zuojj", "male");
// Outputs: Benjamin {sex: "male", username: "zuojj"}
console.log(benjamin);

var ben = Benjamin("zhangsan", "female");
// Outputs: Benjamin {username: "zhangsan", sex: "female"}
console.log(ben);

這種自動補 new 的寫法很方便,但也容易養成坏习惯。更嚴謹的做法是直接丟出錯誤,逼迫呼叫端修正:

function Benjamin(username, sex) {
  // Check whether "this" is a "Benjamin" object
  if (this instanceof Benjamin) {
      this.username = username;
      this.sex = sex;
  } else {
    // If not, throw error.
    throw new Error("`Benjamin` invoked without `new`");
  }
}

二、作為物件方法呼叫時,this 指向該物件

var x = 10;
var obj = {
  x: 10,
  output: function() {
    // Outputs: true
    console.log(this === obj);
    return this.x;
  },
  innerobj: {
    x: 30,
    output: function() {
      // Outputs: true
      console.log(this === obj.innerobj);
      return this.x;
    }
  }
};

// Outputs: 10
console.log(obj.output());
// Outputs: 30
console.log(obj.innerobj.output());

誰呼叫它,this 就指向誰,嵌套物件也不例外。

三、單純呼叫函數時,this 指向全域物件

最常見的踩雷點出現在閉包裡:

var x = 100;
var obj = {
  x: 10,
  output: function() {
    (function() {
      // Outputs: true
      console.log(this === window);
      // Outputs: Inner: 100
      console.log("Inner:" + this.x);
    })();

    return this.x;
  }
};
// Outputs: 10
console.log(obj.output());

立即執行函數建立了自己的作用域,this 因此指向 window(瀏覽器環境)。另一個常見陷阱是把方法「拆下來」單獨呼叫:

var x = 100;
var obj = {
  x: 10,
  output: function() {
    return this.x;
  }
};
var output = obj.output;
// Outputs: 10
console.log(obj.output());
// Outputs: 100
console.log(output());

var obj2 = {
  x: 30,
  output: obj.output
}
// Outputs: 30
console.log(obj2.output());

關鍵在於:this 永遠取決於「呼叫那一刻所屬的物件」,而不是函數在哪裡被定義。

四、透過 call/apply 明確指定

var x = 100;
var obj = {
  x: 10,
  output: function() {
    return this.x;
  }
};
// Outputs: 10
console.log(obj.output());

var obj2 = {
  x: 40,
  output: obj.output
}
// Outputs: 40
console.log(obj.output.call(obj2));
// Outputs: 10
console.log(obj2.output.apply(obj));

call 與 apply 的第一個參數就是 this 的指定對象,這也是「借用方法」的基礎。

五、事件回呼函數中的 this

// <input type="text" value="3" id="txt_username">
$("#username").on("click", function() {
  console.log(this.value);
});

回呼函數內的 this 指向觸發該回呼的物件,這裡就是被點擊的 input 元素。

六、bind 方法:把 this 固定下來

MDN 的定義是:bind() 會建立一個新函數,呼叫時其 this 被設定為指定的值,並在呼叫新函數時於任何傳入參數之前預先帶入一組參數。

function person() {
  return this.name;
}
// Function.prototype.bind
var per = person.bind({
  name: "zuojj"
});
console.log(per);

var obj = {
  name: "Ben",
  person: person,
  per: per
};
// Outputs: Ben, zuojj
console.log(obj.person(), obj.per());
this.x = 9;
var module = {
   x: 81,
   getX: function() { return this.x; }
};
// Outputs: 81
console.log(module.getX());

var getX = module.getX;
// Outputs: 9, because in this case, "this" refers to the global object
console.log(getX);

// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
// Outputs: 81
console.log(boundGetX());

bind 不會改變原函數,而是回傳一個 this 已被綁定的新函數,因此在處理事件監聽、 setTimeout 回呼等容易失去 this 的場合特別實用。

小結

判斷 this 指向時,依序問自己:是否用 new 呼叫?是否用 call/apply/bind 指定?是否作為某物件的方法呼叫?以上皆非,那就是單純呼叫,this 指向全域物件(嚴格模式下則為 undefined)。

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