jquery--call()&apply()函式
1. 定義
call方法
語法:call([thisObj[,arg1[,arg2[,[,..argN]]]]])
定義:呼叫一個物件的一個方法,以另一個物件替換當前物件
說明:call 方法可以用來代替另一個物件呼叫一個方法。call 方法可將一個函式的物件上下文從初始的上下文改變為由 thisObj 指定的新物件。
如果沒有提供 thisObj 引數,那麼 Global 物件被用作 thisObj。
apply方法
語法:apply([thisObj[,argArray]])
定義:應用某一物件的一個方法,用另一個物件替換當前物件。
說明: 如果 argArray 不是一個有效的陣列或者不是 arguments 物件,那麼將導致一個 TypeError。
如果沒有提供 argArray 和 thisObj 任何一個引數,那麼 Global 物件將被用作 thisObj, 並且無法被傳遞任何引數。
2. 常用示例
function add(a,b)
{
alert(a+b);
}
function sub(a,b)
{
alert(a-b);
}
add.call(sub,3,1);
用 add 來替換 sub,add.call(sub,3,1) == add(3,1) ,所以執行結果為:alert(4); // 注意:js 中的函式其實是物件,函式名是對 Function 物件的引用。
function Animal(){
this.name = "Animal";
this.showName = function (){
alert(this.name);
}
}
function Cat(){
this.name = "Cat";
}
var animal = new Animal();
var cat = new Cat();
//通過call或apply方法,將原本屬於Animal物件的showName()方法交給物件cat來使用了。
//輸入結果為"Cat"
animal.showName.call(cat,",");
//animal.showName.apply(cat,[]);
把 animal 的方法放到cat上執行,原來cat是沒有showName() 方法,現在是把animal 的showName()方法放到 cat上來執行,所以this.name 應該是 Cat
3.實現繼承
function Animal(name){
this.name = name;
this.showName = function(){
alert(this.name);
}
}
function Cat(name){
Animal.call(this, name);
}
var cat = new Cat("Black Cat");
cat.showName();
Animal.call(this) 的意思就是使用 Animal物件代替this物件,那麼 Cat中不就有Animal的所有屬性和方法了嗎,Cat物件就能夠直接呼叫Animal的方法以及屬性了.
4.多重繼承
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);
}
當然,js的繼承還有其他方法,例如使用原型鏈,這個不屬於本文的範疇,只是在此說明call 的用法。說了call ,當然還有 apply,這兩個方法基本上是一個意思,區別在於 call 的第二個引數可以是任意型別,而apply的第二個引數必須是陣列,也可以是arguments
還有 callee,caller..