DIV CSS 佈局教程網

JS 中改變 this 指向的三種方法:call、apply、bind
編輯:關於JavaScript     

this 是 JavaScript 的關鍵字,它的值會隨函數的使用場合而變化。但有一條總原則:this 指向調用該函數的那個對象。理解這一點,就能理解絕大多數「this 怎麼變了」的困惑。

默認情況下 this 指向當前調用者,但我們也可以主動改變它。下面介紹三種方式。

一、call 用作繼承

function Parent(age) {
  this.name = ['mike', 'jack', 'smith'];
  this.age = age;
}

function Child(age) {
  Parent.call(this, age);   // 把 Parent 中的 this 指向 Child 實例,同時傳參
}

var test = new Child(21);
console.log(test.age);    // 21
console.log(test.name);   // ['mike','jack','smith']

test.name.push('bill');
console.log(test.name);   // ['mike','jack','smith','bill']

這是最經典的用法:在子類構造函數裡調用 Parent.call(this, ...),相當於借用了父類的構造邏輯,同時保證 this 落在子類實例上。

二、call 與 apply 都能改變 this

兩者的唯一區別在參數形式:apply 的第二個參數必須是數組(或類數組),call 則需要把參數逐個列舉。

console.log(Math.max.apply(null, [1, 2, 3, 4]));   // 4

apply() 接收兩個參數:一個是在其中運行函數的作用域(this 值),另一個是參數數組,可以是 Array 實例也可以是 arguments 對象。call() 的第一個參數同樣是 this 值,區別在於其餘參數直接依次傳給目標函數,因此必須一個個寫出來。

三、ES5 新增的 bind

bind() 會創建一個函數實例,其 this 被永久綁定到傳入的值上:

window.color = 'red';
var o = { color: 'blue' };

function sayColor() {
  console.log(this.color);
}

var objectSayColor = sayColor.bind(o);
objectSayColor();   // blue

這裡 sayColor() 調用 bind() 並傳入對象 o,創建出 objectSayColor()。它的 this 恆等於 o,所以即便在全局作用域下調用,輸出的仍是 blue。

補充:call 與 apply 的定義對比

call 方法
語法:call(thisObj, Object)
定義:調用一個對象的方法,以另一個對象替換當前對象。
說明:call 可將函數的上下文從初始對象改為 thisObj 指定的新對象。若未提供 thisObj,則 Global 對象作為 thisObj。

apply 方法
語法:apply(thisObj, [argArray])
定義:應用某一對象的方法,用另一個對象替換當前對象。
說明:若 argArray 不是有效數組或 arguments 對象,會拋出 TypeError。若 thisObj 與 argArray 都未提供,則 Global 對象作為 thisObj,且無法傳入任何參數。

function Animal(name) {
  this.name = name;
  this.showName = function () { console.log(this.name); };
}

function Cat(name) {
  Animal.call(this, name);        // 逐個傳參
}
Cat.prototype = new Animal();

function Dog(name) {
  Animal.apply(this, name);       // 注意:這裡應傳數組,如 [name]
}
Dog.prototype = new Animal();

var cat = new Cat("Black Cat");
var dog = new Dog(["Black Dog"]);

cat.showName();
dog.showName();

console.log(cat instanceof Animal);   // true
console.log(dog instanceof Animal);   // true

模擬 call 的 this 替換原理

理解了「this 指向調用者」這條規則,就能自己實現一個簡化版的 call:

function Animal(name) {
  this.name = name;
  this.showName = function () { alert(this.name); };
}

function Cat(name) {
  this.superClass = Animal;    // 把 Animal 掛成當前對象的臨時方法
  this.superClass(name);       // 此時 this 就是 Cat 實例
  delete this.superClass;      // 用完清理,避免污染
}

var cat = new Cat("Black Cat");
cat.showName();

思路一目了然:既然 this 由調用方式決定,那就把目標函數臨時變成某對象的方法再調用一次,用完再刪掉。原生 call/apply 的內部實現思路與此同源,只是處理了更多邊界情況。

最後記一條選型口訣:要繼承用 call,參數是數組用 apply,需要固定 this 且後續反覆調用則用 bind。

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