js中,object.call(target)函数用于改变this的指向,实例object调用时候call时,object的this不再指向object,而指向target
1.下例中call将say方法中的this由cat1改为了dog2
function cat(){ } //原型扩展 cat.prototype={ food:"fish", say: function(){ alert("I love "+this.food); } } var cat1 = new cat(); cat1.say(); //当我需要一条狗也说它喜欢什么时,可以定义say方法,也可以通过call用cat1的say方法,如下 dog2 = {food:"bone"}; cat1.say.call(dog2);
2.对象替换
function NameShowing(){
this.showName = function(){//此行的this将被target替代
document.write(this.name);
}
}
function Person(name){
this.name = null;
this.age = function(){
alert(aaa);
}
this.Init = function(name){
this.name = name;
}
this.Init(name);
};
var jeremy = new Person("Jeremy");
//call将NameShowing的this指向jeremy,相当于执行了jeremy.showName=function(){document.write(this.name);}使得jeremy实例拥有了showName方法
NameShowing.call(jeremy);
jeremy.showName();
3.方法替换
function NameShowing(){
this.showName = function(){
document.write(this.name); //此行this将被target替换
}
}
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")
//替换showName中的this指向 jeremy
nameShowing.showName.call(jeremy);
4.构造函数
function Person(name, age){
this.name = null;
this.age = null;
this.showPersonInfo = function(){
document.write("Name: " + this.name + "");
document.write("Age: " + this.age + "");
};
this.Init = function(){
this.name = name;
this.age = age;
};
this.Init();
}
var jeremy = new Object();
Person.call(jeremy, "Jeremy", 20);
//相当于将Person函数中的this替换为jeremy,并执行一遍Person函数
//function Person(obj, name, age){
// obj.name = null;
// obj.age = null;
// obj.showPersonInfo = function(){
// document.write("Name: " + this.name + "");
// document.write("Age: " + this.age + "");
// };
// obj.Init = function(){
// this.name = name;
// this.age = age;
// };
// obj.Init();
//}
//Person(jeremy, "Jeremy", 20);
jeremy.showPersonInfo();
ES6 JavaScript object.call(target)函数的作用
原文:https://www.cnblogs.com/bmxxfvlog/p/14801561.html