call和apply的作用都是改變this的指向楞件,不同的是:
??call第一個(gè)參數(shù)是函數(shù)運(yùn)行的作用域兴蒸,第二個(gè)參數(shù)是函數(shù)的各個(gè)參數(shù)
??apply第一個(gè)參數(shù)和call一樣视粮,第二個(gè)參數(shù)是一個(gè)數(shù)組
call的用法:
//例1
window.color = 'red';
document.color = 'yellow';
var s1 = {color: 'blue' };
function changeColor(){
console.log(this.color);
}
changeColor.call(); //red (默認(rèn)傳遞參數(shù))
changeColor.call(window); //red
changeColor.call(document); //yellow
changeColor.call(this); //red
changeColor.call(s1); //blue
//例2
var Pet = {
words : '...',
speak : function (say) {
console.log(say + ''+ this.words)
}
}
Pet.speak('Speak'); // 結(jié)果:Speak...
var Dog = {
words:'Wang'
}
//將this的指向改變成了Dog
Pet.speak.call(Dog, 'Speak'); //結(jié)果: SpeakWang
apply的用法:
//例1
window.number = 'one';
document.number = 'two';
var s1 = {number: 'three' };
function changeColor(){
console.log(this.number);
}
changeColor.apply(); //one (默認(rèn)傳參)
changeColor.apply(window); //one
changeColor.apply(document); //two
changeColor.apply(this); //one
changeColor.apply(s1); //three
//例2
function Pet(words){
this.words = words;
this.speak = function () {
console.log( this.words)
}
}
function Dog(words){
//Pet.call(this, words); //結(jié)果: Wang
Pet.apply(this, arguments); //結(jié)果: Wang
}
var dog = new Dog('Wang');
dog.speak();