DIV CSS 佈局教程網

JavaScript this 指向完全解析:四種情境一次講清
編輯:關於JavaScript     

this 是 JavaScript 最容易搞混的概念之一。好消息是規則其實很清楚:this 的值取決於「函式是怎麼被呼叫的」,而不是它寫在哪裡。本文用四種情境逐一說明。

一、全域呼叫:this 指向 window

alert(this); // [object Window]

function sayHello() { alert(this); }
sayHello();  // [object Window]

在瀏覽器中直接呼叫一個函式(不屬於任何物件),this 就是全域物件 window。注意:在 strict mode 下,這種情況的 this 會是 undefined 而非 window。

二、方法呼叫:this 指向該物件

var user = "the Window";
var box = {
  user: 'the box',
  getThis:  function() { return this.user; },
  getThis2: function() { return function() { return this.user; } }
};

alert(this.user);              // the Window
alert(box.getThis());          // the box
alert(box.getThis2()());       // the Window(閉包中的 this 回到全域)
alert(box.getThis2().call(box)); // the box(用 call 改寫 this)

重點在第三行:getThis2 回傳的是一個匿名函式,而這個匿名函式是被「直接呼叫」的,所以它的 this 依規則一指向 window。這不是閉包造成的,而是「呼叫方式」造成的——很多人誤解了這一點。

三、call 與 apply:手動指定 this

function sum(num1, num2) { return num1 + num2; }

function box(num1, num2) {
  return sum.apply(this, [num1, num2]); // 用 this 作為 sum 的 this
}
console.log(box(10, 10)); // 20

call(thisArg, arg1, arg2) 與 apply(thisArg, argsArray) 的效果相同,差別只在參數傳遞方式:call 逐一列舉,apply 收在陣列裡。它們是第一個參數用來指定 this 的,其餘參數原封不動轉給目標函式。

四、new 呼叫:this 指向新建立的物件

function Person() {
  console.log(this); // 指向剛建立的新空物件
}
var p = new Person();

用 new 呼叫時,JavaScript 會先建立一個空物件、把它綁到 this、執行函式本體,最後回傳該物件(除非函式自己回傳了物件)。

還有一個經典陷阱:閉包中的 this

var name = "The Window";
var object = {
  name: "My Object",
  getNameFunc: function() {
    var that = this;              // 先把 this 存起來
    return function() { return that.name; };
  }
};
alert(object.getNameFunc()()); // My Object

如果不寫 var that = this 而直接在內部函式用 this.name,拿到的會是 "The Window"。這是在 ES6 之前處理 this 的標準手法。

箭頭函式解決了這個問題

箭頭函式沒有自己的 this,它會沿用外層作用域的 this:

var obj = {
  name: 'My Object',
  getName: function() {
    return () => this.name;   // this 沿用外層,即 obj
  }
};
console.log(obj.getName()()); // My Object

這也是為什麼物件方法不該寫成箭頭函式(會失去 this 綁定),而回呼函式則很適合——事件處理、陣列 forEach、setTimeout 裡的 this 問題,大多都被箭頭函式消解得差不多了。

總結一句:看呼叫方式,不看定義位置。直接呼叫看全域、方法呼叫看物件、new 看新物件、call/apply/bind 看指定值、箭頭函式看外層。

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