javascript 中call用處不少,用壹句話概括就是動態改變this.比如說:
function?cat(){}
//做壹個原型擴展
cat.prototype={
food:"fish",
say:?function(){
alert("I?love?"+this.food);
}
}
var?blackCat?=?new?cat;
blackCat.say();
//當我需要壹條黑狗也說它喜歡什麽時:
blackDog?=?{food:"bone"};
//我們不想對它重新定義say方法,那麽我們可以通過call用blackCat的say方法:
blackCat.say.call(blackDog);
//例子來源於知乎
call用來改變this的,改變的方式就壹下幾種:
1,上例子中屬於繼承式
2,替換式
function?NameShowing(){?this.showName?=?function(){?
document.write(this.name);?
}?
}?
function?Person(name){?
this.name?=?null;?
this.Init?=?function(name){
this.name?=?name;
}
this.Init(name);
};?
var?nameShowing?=?new?NameShowing();?
var?jeremy?=?new?Person("Jeremy")?
//替換this指向?jeremy
nameShowing.showName.call(jeremy);
3,實例繼承
function?NameShowing(){?this.showName?=?function(){?
document.write(this.name);?
}?
}?
function?Person(name){?
this.name?=?null;?
this.Init?=?function(name){
this.name?=?name;
}
this.Init(name);
};?
var?jeremy?=?new?Person("Jeremy")
NameShowing.call(jeremy);?
jeremy.showName();
2和3壹個是針對方法,壹個是對象,本質壹樣。
4,帶有構造函數的參數
function?Person(name,?age){?this.name?=?null;?
this.age?=?null;?
this.showPersonInfo?=?function(){?
document.write("Name:?"?+?this.name?+?"<br>");?
document.write("Age:?"?+?this.age?+?"<br>");?
};?
this.Init?=?function(){?
this.name?=?name;?
this.age?=?age;?
};?
this.Init();?
}?
var?jeremy?=?new?Object();?
Person.call(jeremy,?"Jeremy",?20);?
jeremy.showPersonInfo();
參考資料: