JS中的call()和apply()方法

1、方法定义

call方法: 
语法:call([thisObj[,arg1[, arg2[,   [,.argN]]]]]) 
定义:调用一个对象的一个方法,以另一个对象替换当前对象。 
说明: 
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。 
如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。 

apply方法: 

语法:apply([thisObj[,argArray]]) 
定义:应用某一对象的一个方法,用另一个对象替换当前对象。 
说明: 
如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。 
如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。


用 一个对象 aa来替换bb

function aa(a,b)
{
    alert(a+b);
}
function bb(a,b)
{
    alert(a-b);
}
aa.call(bb,3,1); 
  这个例子中的意思就是用 aa 来替换 bb,aa.call(bb,3,1) == add(3,1) ,所以运行结果为:alert(4); /

 在 js 中的函数其实是对象,函数名是对 Function 对象的引用。


把对象 a 的方法用 对象 b 来执行

function aa(){  
    this.name = "aa";  
    this.show = function(){  
        alert(this.name);  
    }  
}  
function bb(){  
    this.name = "bb";  
}  
var aa = new aa();  
var bb = new bb();  
通过call或apply方法,将原本属于aa对象的show()方法交给对象bb来使用了。  
输入结果为"bb"  

aa.show.call(bb,",");  
aa.show.apply(bb,[]);
实现继承:b 继承 a

function aa(<span style="font-family: Monaco, 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', Consolas, 'Courier New', monospace; line-height: 18px; background-color: rgb(250, 250, 250);">name</span>){  
    this.name = <span style="font-family: Monaco, 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', Consolas, 'Courier New', monospace; line-height: 18px; background-color: rgb(250, 250, 250);">name</span>;  
    this.show = function(){  
        alert(this.name);  
    }  
}  
function bb(name){  
	aa.call(this, name);	
}  
var bb = new bb("bb"); bb.show();
 aa.call(this) 的意思就是使用 aa对象代替this对象,
 那么 bb中就有aa的所有属性和方法,
 bb对象就能够调用aa的方法以及属性.


还可以实现多继承

function aa(name){  
    this.name = name;  
    this.show = function(){  
        alert(this.name);  
    }  
} 
function bb(){   
    this.conut = function(str){  
        alert(this.name + str);  
    }  
}  
function cc(name){  
	aa.call(this, name);	
	bb.call(this);
}  
new cc("11").show();new cc("11").conut("yy");







猜你喜欢

转载自blog.csdn.net/wbxx727124/article/details/50834602