call
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
调用一个对象的一个方法,以另一个对象替换当前对象
apply
apply([thisObj[,argArray]])
应用某一对象的一个方法,用另一个对象替换当前对象。
这2个基本一样,只不过apply的参数是 数组
看下例子就能很轻松的理解了
<p id="p">看看我的颜色和字号</p>
var o = document.getElementById("p");
function a(color,size){
if (this!=window){
this.style.color = color;
this.style.fontSize = size+"px";
}
}
a(); //这个时候this指向的是window
a.call(o,"red",48)//执行call的时候 this指向element了
//a.apply(o,["red",48]) //call和apply的区别在这里
a(); //这个时候还是window了
很简单吧,ok 还可以应用到继承里 看例子
function classA(name,age){
this.name = name;
this.age = age;
}
function classB(name,age,sex){
var _this = this;
_this.sex = sex;
//我要继承classA里的2个属性name,age
classA.call(_this,name,age);// 改变了classA的this指向
//classA.apply(_this,[name,age]); //apply 和call的区别
_this.echo = function(){
alert(_this.name+"\n"+_this.age+"\n"+_this.sex);
}
}
var _obg = new classB("cjg","26","男")
_obg.echo();