首先先說明它們共同的作用:call和apply 都是用來修改函數(shù)中this的指向問題趣席;
其次就是它們不同的傳參方式:注意上一句話中說他們的作用時有兩個關(guān)鍵詞 ‘函數(shù)’和‘this’泊柬,想要修改this 的指向波附,那么必然有一個this修改后的指向,而函數(shù)必然后關(guān)系到傳參問題:call方法可以傳給該函數(shù)的參數(shù)分別作為自己的多個參數(shù)冗美,而apply方法必須將傳給該函數(shù)的參數(shù)合并成一個數(shù)組作為自己的一個參數(shù):
var name = 'Evan';
var age = 20;
var person = {
name: 'Hillary',
age: 19,
sayIntroduce: function () {
return "Hello, My name is " + this.name + " and I'm " + this.age + ' years old.'
},
sayHobby: function (val1, val2) {
return "I'm " + this.name + ", I like " + val1 + " and " + val2 + ".";
}
}
var person1 = {
name: 'Coy'
}
console.log(person.sayIntroduce()); // Hello, My name is Hillary and I'm 19 years old.
當(dāng)我們通過 call 和 apply 來this的指向時魔种,不傳任何參數(shù),則默認(rèn)為將this指向修改為 windows
// 當(dāng)沒有參數(shù)時粉洼,默認(rèn)將this指向 window
console.log(person.sayIntroduce.call()); // Hello, My name is Evan and I'm 20 years old.
console.log(person.sayIntroduce.apply()); // Hello, My name is Evan and I'm 20 years old.
有參數(shù)時节预,this 指向第一個參數(shù):
// 將this指向 person1,由于person1中沒有age屬性属韧,因此為 undefined
console.log(person.sayIntroduce.call(person1)); // Hello, My name is Coy and I'm undefined years old.
console.log(person.sayIntroduce.apply(person1)); // Hello, My name is Coy and I'm undefined years old.
當(dāng)需要傳遞參數(shù)時安拟,call可以直接寫多個參數(shù),apply需要用數(shù)組方式傳遞:
console.log(person.sayHobby.call(person1, 'swimming', 'hiking')); // I'm Coy, I like swimming and hiking.
console.log(person.sayHobby.apply(person1, ['swimming', 'hiking'])); // I'm Coy, I like swimming and hiking.