call
定义:调用一个对象的一个方法,以另一个对象替换当前对象。
var a = {
user:"Ice",
fn:function(){
console.log(this.user);
}
}
a.fn(); //Ice
通过call方法,把b添加到a的环境中,this就会指向a.
apply
定义:应用某一对象的一个方法,用另一个对象替换当前对象。
var a = {
user:"Ice",
fn:function(){
console.log(this.user); //Ice
}
}
var b = a.fn;
b.apply(a);
通过apply方法实现同call方法同样的效果
如果call和apply的第一个参数写的是null,那么this指向的是window对象
区别
call传递多个参数
var a = {
user:"Ice",
fn:function(e,ee){
console.log(this.user); //Ice
console.log(first+second); //3
}
}
var b = a.fn;
b.call(a,1,2);
apply传递多个参数
var a = {
user:"Ice",
fn:function(e,ee){
console.log(this.user); //Ice
console.log(first+second); //3
}
}
var b = a.fn;
b.apply(a,[1,2]);
var a = {
user:"Ice",
fn:function(e,ee){
console.log(this.user); //Ice
console.log(first+second); //3
}
}
var b = a.fn;
var arr = [1,2];
b.apply(a,arr);
apply传递多个参数的时候第二个参数需要传递一个数组
bind
var a = {
user:"Ice",
fn:function(){
console.log(this.user);
}
}
var b = a.fn;
b.bind(a);
bind用来改变this的指向,返回一个修改过的函数,该函数不会被执行
var a = {
user:"Ice",
fn:function(){
console.log(this.user);
}
}
var b = a.fn;
var c = b.bind(a);
c();//Ice
我们需要手动执行新函数
var a = {
user:"Ice",
fn:function(e,d,f){
console.log(this.user); //Ice
console.log(first,second,third); //0 1 2
}
}
var b = a.fn;
var c = b.bind(a,0);
c(1,2);
bind可以由多个参数,并且可以执行的时候添加,按照形参的顺序进行的。
applay和call区别在于传入多个参数是的方法不同,applay、call和bind的却别在于前者立即执行,后者在需要的时候执行。
网友评论