在Mozilla的官網中對于call()的介紹是:
Call() 參數
thisArg
Javascript中的call()方法
先不關注上面那些復雜的解釋,一步步地開始這個過程。
Call()方法的實例
于是寫了另外一個Hello,World:
接著,我們再來看另外一個例子。
print.call(obj, "Hello", "World");
只是在這里,我們傳進去的還是一個undefined,因為上一個例子中的undefined是因為需要傳進一個參數。這里并沒有真正體現call的用法,看看一個更好的例子。
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將指向相關的對象。只是在這個例子中我們沒有看明白,到底是h2調了print,還是print調用了h2。于是引用了Mozilla的例子
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);
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方法可以定義高階函數允許使用者給回調函數指定接收者。
新聞熱點
疑難解答
圖片精選