call和apply用法
call和apply作用就是改变this的指向,可以让一个对象调用其他对象的方法
先看一个例子:
function fun(){
}
fun.prototype={
name:"Mark",
say:function(){
alert("Name is "+this.name)
}
}
var fun1 = new fun();
obj = {
name:"Roy"
}
fun1.say(); //Name is Mark
fun1.say.call(obj); //Name is Roy
这样,obj就具有了fun的say()方法了,这是this.name指的就是"Roy"。
下面看下带参数的call和apply的用法,call和apply的区别就在于第二个参数传递的不一样,call是传递任何类型的,而apply是要数组类型的。
function add(a,b){
alert(a+b);
}
function test(){
alert("test")
}
add.call(test,1,2)
add.apply(test,[1,2])
这个例子中两次都弹出3。
通过call和apply,本来执行test函数是要弹出“test”的,但是通过call/apply就可以让test具有add的方法,也就是执行test时候实际执行的是a+b。
call和apply区别就在于第二个参数的传递,call要分别传递参数,而apply是要传递一个数组。
再来一个例子实现call和apply对函数的继承
function sum(a,b,c,d){
alert(a+b+c+d);
}
function sumInh(a,b,c,d){
sum.call(this,a,b,c,d);
sum.apply(this,arguments);
sum.apply(this,[a,b,c,d])
}
sumInh(1,2,3,4);
这三种方法实现继承的效果是一样的,都是让sumInh拥有sum的方法。
这样继承就直接执行了函数,再来一个例子说明它们在构造函数中的作用。
function sum(){
this.add = function(a,b){
alert(a+b)
}
}
function sub(){
this.sub = function(a,b){
alert(a-b)
}
}
function sumInh(){
sum.call(this);
sub.call(this);
}
var newSunInh = new sumInh();
newSunInh.add(1,2); //3
newSunInh.sub(1,2); //-1
这里sumInh继承了sum和sub两个函数的方法,所以可以当做sumInh函数的方法进行调用。
浙公网安备 33010602011771号