function theFunction(name, profession) {
console.log("My name is " + name + " and I am a " + profession + ".");
}
theFunction("John", "fireman");
theFunction.apply(undefined, ["Susan", "school teacher"]);
theFunction.call(undefined, "Claude", "mathematician");
theFunction.call(undefined, ...["Matthew", "physicist"]);
// Output:
// My name is John and I am a fireman.
// My name is Susan and I am a school teacher.
// My name is Claude and I am a mathematician.
// My name is Matthew and I am a physicist.
记忆法:A for array and C for comma
使用场景:当一个object没有某个方法,但是其他的有,我们可以借助call或apply用其它对象的方法来操作。
```js
function Cat() {
}
Cat.prototype = {
food: 'fish',
say: function() {
console.log('I love ' + this.food)
}
}
var cat = new Cat()
cat.say() // I love fish
function Dog() {
}
Dog.prototype = {
food: 'bone'
}
var dog1 = new Dog()
cat.say.call(dog1) // I love bone
var dog2 = {
food: 'beef'
}
cat.say.call(dog2) // I love beef
apply和call都是为了改变函数运行时的上下文而存在的,即改变函数体内部this的指向
区别:
function theFunction(name, profession) { console.log("My name is " + name + " and I am a " + profession + "."); } theFunction("John", "fireman"); theFunction.apply(undefined, ["Susan", "school teacher"]); theFunction.call(undefined, "Claude", "mathematician"); theFunction.call(undefined, ...["Matthew", "physicist"]); // Output:
// My name is John and I am a fireman. // My name is Susan and I am a school teacher. // My name is Claude and I am a mathematician. // My name is Matthew and I am a physicist.
参考: