DIV CSS 佈局教程網

JavaScript call() 方法詳解
編輯:關於JavaScript     

Mozilla 官網對 call() 的介紹是:

復制代碼 代碼如下:
call() 方法在使用一個指定的this值和若干個指定的參數值的前提下調用某個函數或方法.

Call() 語法

復制代碼 代碼如下:
fun.call(thisArg[, arg1[, arg2[, ...]]])

Call() 參數

thisArg

復制代碼 代碼如下:
在fun函數運行時指定的this值。需要注意的是,指定的this值並不一定是該函數執行時真正的this值,如果這個函數處於非嚴格模式下,則指定為null和undefined的this值會自動指向全局對象(浏覽器中就是window對象),同時值為原始值(數字,字符串,布爾值)的this會指向該原始值的自動包裝對象。

arg1, arg2, ...

復制代碼 代碼如下:
指定的參數列表。

JavaScript 中的 call() 方法

先不糾結那些複雜的解釋,一步步來看。

Call() 方法的實例

於是寫了另一個 Hello, World:

復制代碼 代碼如下:
function print(p1, p2) {
    console.log( p1 + ' ' + p2);
}
print("Hello", "World");
print.call(undefined, "Hello", "World");

兩種方式有相同的輸出結果,只是 call 還多傳了一個 undefined。

接著看另一個例子:

復制代碼 代碼如下:
var obj=function(){};
function print(p1, p2) {
    console.log( p1 + ' ' + p2);
}

print.call(obj, "Hello", "World");

這裡傳進去的仍是一個 undefined,因為上一個例子中的 undefined 只是為了佔位。這裡並未真正體現 call 的用法,看看更好的例子:

復制代碼 代碼如下:
function print(name) {
    console.log( this.p1 + ' ' + this.p2);
}

var h={p1:"hello", p2:"world", print:print};
h.print("fd");

var h2={p1:"hello", p2:"world"};
print.call(h2, "nothing");

call 的用法就是借用別人的方法或物件來呼叫,就像呼叫自己的一樣。在 h.print 中,將函式作為方法呼叫時,this 會指向相關的物件。於是引用 Mozilla 的例子:

復制代碼 代碼如下:
function Product(name, price) {
    this.name = name;
    this.price = price;

    if (price < 0)
        throw RangeError('Cannot create product "' + name + '" with a negative price');
    return this;
}

function Food(name, price) {
    Product.call(this, name, price);
    this.category = 'food';
}
Food.prototype = new Product();

var cheese = new Food('feta', 5);
console.log(cheese);

在這個例子中,用 Food 建構子建立的物件都會擁有 Product 中加入的 name 與 price 屬性,而 category 則在各自的建構子中定義。這清楚展現了 call 用於繼承的用法。

復制代碼 代碼如下:
function print(name) {
    console.log( this.p1 + ' ' + this.p2);
}

var h2= function(no){
    this.p1 = "hello";
    this.p2 = "world";
    print.call(this, "nothing");
};
h2();

這裡的 h2 作為接收者來呼叫函式 print。正如 Food 的例子,在子建構子中,你可以透過呼叫父建構子的 call 方法來實作繼承。

至於 call 方法的優點,《Effective JavaScript》中有歸納:1. 使用 call 自訂接收者來呼叫函式;2. 使用 call 可呼叫在給定物件中不存在的方法;3. 使用 call 可定義高階函式,允許使用者為回調函式指定接收者。

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