
正文
js中call和apply的作用和用法
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
call和apply的用途是完全一样的。改变函数中this的指向:
为什么要改变this的指向呢?这个有什么用?有哪些场景呢?
首先this的指向总是在变的,this的指向是由函数执行时所在的环境决定的,而不是函数声明时的环境。
this都指向哪里?
1、在控制台中输入下面的代码,此时可以看到this指向a这个对象。
var a={
name:'a',
getName:function(){
return this.name;
}
}
console.info(a.getName());//a
2、此时this指向了window
window.name= 'window';
var a={
name:'a',
getName:function(){
return this.name;
}
} var b = a.getName;
console.info(b());//window
结论:
如果函数是作为一个对象的属性被调用的(用点的方式调用),此时函数内的this就指向这个对象。
如果是用变量或者名称的方式直接调用的(不是使用点调用),则指向window。
场景:
this的改变:在写代码时经常会遇到这种情况,将函数作为回调函数使用时,this的指向变为了window,这个不是我们预期的结果
window.name='window';
var a={
name:'a',
getName:function(callback){
return callback();//funcB使用非对象.的方式调用
},
funcB:function(){
return this.name;
}
}
console.info(a.getName(a.funcB));//window
这个时候就可以用call或者apply把this传递到callback中,callback中的this的指向就会被传入的this所替代。
当然,也可以传入其他对象覆盖当前this的指向。
window.name='window';
var b={
name:'b'
};
var a={
name:'a',
getName:function(callback){
return callback.call(b);//传入b
},
funcB:function(){
return this.name;
}
}
console.info(a.getName(a.funcB));//b
也可以借用这个对象的方法。
window.name='window';
var b={
name:'b',
getBName:function(){
return this.name;
}
};
var a={
name:'a',
getName:function(callback){
return callback.call(b);//传入b
},
funcB:function(){
return this.getBName();
}
}
console.info(a.getName(a.funcB));//b
使用这个功能可以实现类似继承的效果
var F=function(name){
this.name = name;
}
var S = function(){
this.age=arguments[];
F.apply(this,arguments);
}
S.prototype.getNameAndAge=function(){
console.info('名字是'+this.name+'年龄是'+this.age);
}
var s = new S('小红','9岁');
s.getNameAndAge();//名字是小红年龄是9岁
call和apply的区别:
传入的参数形式不一样
call(obj,参数1,参数2);
apply(obj,[参数1,参数2]);





