美文网首页
call() && apply() 实例

call() && apply() 实例

作者: 林键燃 | 来源:发表于2018-10-10 17:18 被阅读13次

实例

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...])

相关文章

网友评论

      本文标题:call() && apply() 实例

      本文链接:https://www.haomeiwen.com/subject/fdhmaftx.html