1、它是函数的方法或属性;
2、它可以改变执行上下文的this指向;
3、作为另一个对象调用一个方法(即可以把一个对象的方法作为另一个对象的方法来引用);
4、apply方法类似,但只能接收数组为参数;
5、callee函数的调用者。
call方法:
语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])
定义:调用一个对象的一个方法,以另一个对象替换当前对象。
说明:
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。
如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。
apply方法:
语法:apply([thisObj[,argArray]])
定义:应用某一对象的一个方法,用另一个对象替换当前对象。
说明:
如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。
如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。
f.call(o,1,2) 等同于
o.m = f;
o.m(1,2);
例1:
function o1(value){
if(value < 100){
this.value = value;
}else{
this.value = 100;
}
}
function o2(value){
o1.call(this,value);
alert(this.value);
}
var o = new o2(133554) //100 改变了this的指向
例2:
function c1(){
this.m1 = function(){
alert(this.name);
}
}
function c2(){
this.name = “mike”;
}
var nc1 = new c1();
var nc2 = new c2(); //必须
nc1.m1.call(nc2); //mike 把方法m1作为对象nc2的方法来引用
例3:
function o1(arg){
if (arguments[1] < 100) {
this.value = arguments[1] ;
}
else {
this.value = 100;
}
}
function o2(arg){
o1.apply(this, arg);
alert(this.value);
}
var o = new o2([101,60]) //60 参数只能是数组
callee用法,常用于匿名函数中
var factorial = function(x){
if(x <= 1){
return 1;
}
return x * arguments.callee(x - 1);
}
alert(factorial(5)); //120
----------------------------------------------------其他例子
<script language="javascript" type="text/javascript" >
function man(name){
this.name=name;
this.setName=function(n){
this.name=n;
};
this.getName=function(){
return this.name;
}
}
function person(nation){
this.nation=nation;
this.setNation=function(n){
this.nation=n;
};
this.getNation=function(){
return this.nation;
}
}
function extend(subobj,supobj,parm){
supobj.call(subobj.prototype,parm);
}
extend(man,person,"china");
var m=new man('sidihu');
alert(m.getName());
m.setNation('england');
alert(m.getNation());
</script>
<script language="javascript" type="text/javascript" >
function man(name){
this.name=name;
this.setName=function(n){
this.name=n;
};
this.getName=function(){
return this.name;
}
}
function person(nation){
this.nation=nation;
this.setNation=function(n){
this.nation=n;
};
this.getNation=function(){
return this.nation;
}
}
function extend(subobj,supobj,parm){
supobj.call(subobj.prototype,parm);//
}
extend(man,person,"china");
var m=new man('sidihu');
alert(m.getName());
m.setNation('england');
alert(m.getNation());
</script>
<script language="javascript" type="text/javascript" >
function baseClass(){
this.parm="this is baseClass";
this.showParm=function(){
alert(this.parm);
}
this.showParm2=function(){
alert("showParm2"+this.parm);
}
}
function class2(){
this.parm="this is class2";
}
var p=new baseClass();
p.showParm()
</script>