1.call和apply的区别
apply传入数组,call依次传入参数,两者第一个参数都是this
2.用途
1).改变this指向
name = "tom";
var obj1 = {
name: "anne",
getName(){
console.log(this.name);
}
};
var obj2 = {
name: "seven"
};
var getName = function(){
console.log("this.name:",this.name);
}
getName(); //tom
getName.call(obj1); //anne
getName.call(obj2); //seven
obj1.getName.call(obj2); //seven
//修正this的指向
document.getElementById( 'div1' ).onclick = function(){
var func = function(){
alert ( this.id );
}
func.call( this ); // 输出:div1
};
2).bind的实现
Function.prototype.bind = function( context ){
var self = this;
return function(){
//返回对象的时候,this指向该对象
return self.apply( context, arguments );
}
};
var obj = {
name: 'sven'
}
var func = function(){
console.log(this.name); //sven
};
func().bind(obj);
3).借用其他对象的方法
var A = function( name ){
this.name = name;
}
var B = function(){
A.apply(this, arguments);
}
B.prototype.getName = function(){
return this.name;
}
var b = new B('sevn');
console.log(b.getName()); //'sven'
//对象借用数组的push方法
var a = {};
Array.prototype.push.call(a,'first');
console.log(a); //{ '0': 'first', length: 1 }
网友评论