DIV CSS 佈局教程網

通俗易懂談 this 指向:四種場景一次講清
編輯:JavaScript基礎知識     

JavaScript 的 this 之所以讓人頭痛,是因為它在運行期才被綁定,同一個 this 在不同呼叫方式下指向完全不同的東西。但只要掌握四種呼叫模式,一切就清晰了。

四種基本場景

  1. 作為物件的方法呼叫:obj.a()
  2. 作為普通函數呼叫:a()
  3. 作為建構函數呼叫:new a()
  4. 透過 call / apply 呼叫

場景一、二:方法呼叫 vs 普通函數呼叫

window.a = 2;
var obj = {
  a: 1,
  getA: function () { console.log(this.a); }
};

obj.getA();   // 輸出 1,作為物件方法,this 指向 obj

var x = obj.getA;
x();          // 輸出 2,作為普通函數,this 指向 window

關鍵規則:無論 x 之前是誰的屬性,只要最後是以 x()、fun() 這種「裸呼叫」形式執行,就視為普通函數呼叫,this 指向 window。

但在 ES5 的 strict mode 下,普通函數呼叫的 this 不再指向全域物件,而是 undefined:

window.a = 2;
var obj = {
  a: 1,
  getA: function () {
    "use strict"
    console.log(this.a);
  }
};
var x = obj.getA;
x();   // undefined

場景三:建構函數呼叫

用 new 呼叫時,this 通常指向新建立的物件。但有個例外:如果建構函數顯式 return 了一個物件,那 this 就指向那個回傳的物件。

var MyClass = function () {
  this.name = 'beidan';
};
var obj = new MyClass();
console.log(obj.name);   // "beidan"

var MyClass2 = function () {
  this.name = 'beidan';
  return {              // 顯式回傳物件,name 被覆蓋
    name: 'test'
  };
};
var obj2 = new MyClass2();
console.log(obj2.name);  // "test"

注意兩個條件必須同時成立:一是有 return,二是回傳的是物件型別。若回傳的是基本型別,則會被忽略。

場景四:call 與 apply

兩者的作用完全相同——改變函數體內部 this 的指向,差別只在參數的傳遞形式:

func1.call(this, arg1, arg2);     // 參數逐一列出
func1.apply(this, [arg1, arg2]);  // 參數放進陣列

第一個參數決定函數體內 this 的指向,可以是任何 JavaScript 物件;若傳 null,this 會退回預設的宿主物件(瀏覽器中為 window)。當參數數量不確定時用 apply,把參數 push 進陣列再傳入即可,也可以直接用 arguments。

用途一:修正 this 指向

document.getElementById('div1').onclick = function () {
  console.log(this.id);   // "div1"
  var func = function () {
    console.log(this.id);
  };
  func();                 // undefined,普通函數呼叫指向 window
  func.call(this);        // "div1",用 call 把 this 拉回外層函數
};

用途二:借用其他物件的方法

function Fruits() {}
Fruits.prototype = {
  color: "red",
  say: function () { console.log("My color is " + this.color); }
};

var apple = new Fruits();
apple.say();   // "My color is red"

var banana = { color: "yellow" };
var orange = { color: "orange" };

apple.say.call(banana);    // "My color is yellow"
apple.say.apply(orange);   // "My color is orange"

也就是說,當某個物件缺少某方法(banana 沒有 say),而另一個物件有(apple 有 say),就可以透過 call / apply 借用。這正是「模擬繼承」的基礎。

用途三:求陣列的最大最小值

var numbers = [5, 458, 120, -215];
var maxInNumbers = Math.max.apply(Math, numbers);        // 458
var maxNumbers = Math.max.call(Math, 5, 458, 120, -215, 666); // 666

Math.max 本身不接受陣列,但 numbers 沒有 max 方法,Math 有——apply 剛好把陣列攤平成參數列表,完美解決。

速記口訣

  • 誰呼叫,this 就是誰(方法呼叫)
  • 裸呼叫,this 指向 window(strict mode 下為 undefined)
  • new 呼叫,this 指向新物件(除非顯式回傳物件)
  • call / apply 可以任意指定 this

掌握這四條,加上箭頭函數「this 繼承自外層作用域」這條 ES6 規則,實務上的 this 問題基本都能應對。

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