call() && apply() 实例

2018-10-10  本文已影响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对象,而不同的是其它参数传入的形式。

上一篇 下一篇

猜你喜欢

热点阅读