call和apply
obj.call(thisObj,arg1,arg2,…)
定义:用thisObj对象替代obj,调用obj的方法
说明:call方法可以用来替代另一个对象调用一个方法。call方法可将一个函数的对象从初始的上下文改变为thisObj指定的新对象。如果没有提供obj2参数,那么Global对象被用作obj。
obj.apply(thisObj,arg1,arg2,…)
定义:用thisObj对象来替代obj,调用obj的方法。即将obj的方法应用到thisObj上
说明:calll()和apply()作用一样,但是call()可以接受任何类型的参数,而apply()智能接受数组参数。apply最多只能有两个参数,新的this对象和一个数组argArray。如果给该方法传递多个参数,则把这个参数写进数组里面,即使只有一个参数,也要写进数组里面。如果argArrayn不是一个有效数组或者不是argments对象,将导致一个TypeError。如果没有提供argArray和thisObj任何一个参数,那么Global对象将被用作thisObj,并且无法传递任何参数
示例:
function father(){
this.name = "小胡",
this.answer = function(){
alert("我是你爸"+this.name);
}
}
function daughter(){
this.name = "老胡",
this.ask = function(){
alert("楼上那位你谁呀");
}
}
var father = new father();
var daughter = new daughter();
father.answer.call(daughter); //我是你爸小胡
father.answer.apply(daughter);//我是你爸小胡
father.answer.call(daughter) 是用daughter替换了father这个对象,调用了father对象中answer这个方法,但当前this指代的daughter这个对象,所以this.name显示的是老胡。
call(apply)实现调用原生对象方法
var book = {
0:1,
1:"xiaohu",
length:2
};
// book.slice(); book.slice is not a function
console.log(Array.prototype.slice.call(book));//输出[1,"xiaohu"]
通过call和apply,我们可以实现对象继承
var Parent = function(){
this.name = "laohu",
this.age = 50
}
var daughter = {};
console.log(daughter);//输出{}
Parent.call(daughter);
console.log(daughter);//输出{name:"laohu",age:50}
补充bind的使用
obj.bind(thisObj,arg1,arg2,…)
将obj绑定到thisObj,这时候thisObj具备了obj的属性和方法。与call和apply不同的是,bind绑定之后不会立即执行。如果bind的第一个参数是null或者undefined,等于将this绑定到全局对象
function add(j,k){
return j+k;
}
function sub(){
return j-k;
}
add(5,3);
console.log(add.call(sub,5,3));//8
console.log(add.bind(sub,5,3));// f add(j,k){ return j+k;}
console.log(add.bind(sub,5,3)());//8