//javascript 中call用处不少,用一句话概括就是动态改变this.比如说:
/*------------------------------1 继承式-----------------------------*/
function cat(){
}
//做一个原型扩展
cat.prototype={
food:"fish",
say: function(){
console.log("I love "+this.food);
}
}
var blackCat = new cat;
blackCat.say();
//当我需要一条黑狗也说它喜欢什么时:
blackDog = {food:"bone"};
//我们不想对它重新定义say方法,那么我们可以通过call用blackCat的say方法:
blackCat.say.call(blackDog);
/*----------------------------2 替换式------------------------------*/
function oldName() {
this.oldname = function(){
console.log(this.name)
}
}
function Person(name) {
this.name = null;
this.Init = function (name) {
this.name = name;
}
this.Init(name);
}
var oneName = new oldName();
var lutong = new Person('lutong')
oneName.oldname.call(lutong)
/*--------------------------3 继承式----------------------------------*/
function NameShowing(){
this.showName = function(){
console.log(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();
/*-----------------4 带有构造函数的参数 -------------------- */
function Person(name, age){
this.name = null;
this.age = null;
this.showPersonInfo = function(){
console.log("Name: " + this.name + "");
console.log("Age: " + this.age + "");
};
this.Init = function(){
this.name = name;
this.age = age;
};
this.Init();
}
var jeremy = new Object();
Person.call(jeremy, "Jeremy", 20);
jeremy.showPersonInfo();