DIV CSS 佈局教程網

JavaScript 的 call() 與 apply():定義、差異與實戰範例
編輯:JavaScript基礎知識     

方法定義

call

語法:call([thisObj[, arg1[, arg2[, ... argN]]]])

用另一個物件的身分去呼叫某個函式,也就是把函式的 this 上下文從原本物件換成 thisObj。若未提供 thisObj,則以全域物件代替(在嚴格模式下為 undefined)。

apply

語法:apply([thisObj[, argArray]])

作用與 call 完全相同,差別只在參數傳遞形式:第二個參數必須是陣列或 arguments 物件,否則會拋出 TypeError。兩者都不傳時,以全域物件作為 thisObj,且無法傳入任何參數。

實戰範例

a. 借用其他函式的上下文

function add(a, b) { alert(a + b); }
function sub(a, b) { alert(a - b); }

add.call(sub, 3, 1);        // 輸出 4

這裡的意思是用 add 的邏輯、以 sub 作為 this 來執行,等效於 add(3, 1)。要牢記的是:JavaScript 的函式本身就是物件,函式名只是對 Function 物件的一個參照。

b. 讓 A 物件使用 B 物件的方法

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

var animal = new Animal();
var cat = new Cat();

animal.showName.call(cat);      // 輸出 "Cat"
// animal.showName.apply(cat, []);   // 等效寫法

call 把 animal 的 showName 放到 cat 身上執行,因此函式內的 this 變成 cat,this.name 自然是 "Cat"。原本 cat 並沒有這個方法,是暫時「借」來的。

c. 實現繼承

function Animal(name) {
  this.name = name;
  this.showName = function () { alert(this.name); };
}
function Cat(name) {
  Animal.call(this, name);        // 關鍵:把 this 交給父構造器
}

var cat = new Cat('Black Cat');
cat.showName();                   // Black Cat

Animal.call(this, name) 相當於讓 Animal 構造器以「新的 Cat 實例」為 this 執行一次,於是 name 屬性與 showName 方法都被掛到這個實例上。這種做法被稱為「偽經典繼承」或構造器借用。

d. 多重繼承

function Class10() {
  this.showSub = function (a, b) { alert(a - b); };
}
function Class11() {
  this.showAdd = function (a, b) { alert(a + b); };
}
function Class2() {
  Class10.call(this);
  Class11.call(this);
}

連續兩個 call 就湊出了多重繼承的效果。

總結

  • 相同點:兩者都能改變函式執行時的 this 指向,效果等價。
  • 不同點:傳參方式不同。call 逐一列出參數,apply 接收一個陣列或 arguments。當參數數量不確定時用 apply(例如 Math.max.apply(null, arr))會方便得多。

JavaScript 的繼承還有原型鏈、Object.create、class 與 extends 等方式,不在本文範圍內。順帶一提,arguments.callee 與 arguments.caller 這兩個屬性在嚴格模式下已被禁用,不建議使用;ES5 之後更有 bind 可以產生永久綁定 this 的新函式。

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