call() && apply() 实例

实例

call() 方法

call() 简单用法: 传入指定对象,改变 this 指向

window.color = 'red';
document.color = 'yellow';
let obj = {
    color: 'blue'
};   

let changeColor = function() {
    console.log(this.color);
}

changeColor.call(); //red (默认传递 window对象 作为参数)
changeColor.call(window); //red
changeColor.call(document); //yellow
changeColor.call(this); //red (当前位置this指向window对象)
changeColor.call(obj); //blue

apply() 方法

apply() 简单用法: 传入指定对象,改变 this 指向

window.number = 'one';
document.number = 'two';
var obj = { number: 'three' };

function changeNumber(){
   console.log(this.number);
}

changeNumber.apply();  //one (默认传递 window对象 作为参数)
changeNumber.apply(window);  //one
changeNumber.apply(document); //two
changeNumber.apply(this);  //one (当前位置this指向window对象)
changeNumber.apply(obj);     //three

区别

call()apply() 两个方法的第一个参数都是将传入的指定作为当前的this对象,而不同的是其它参数传入的形式。

  • call():call(this对象, 参数1, 参数2, 参数3...)
  • apply(): apply(this对象, [参数1, 参数2, 参数3...])
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容