- 概念
每个函数都包含两个非继承而来的方法:apply()和call()。 call与apply都属于Function.prototype的一个方法,所以每个function实例都有call、apply属性;
- 作用
call()方法和apply()方法的作用相同:改变this指向。
- 区别
他们的区别在于接收参数的方式不同: call():第一个参数是this值没有变化,变化的是其余参数都直接传递给函数。在使用call()方法时,传递给函数的参数必须逐个列举出来。 apply():传递给函数的是参数数组
- 应用
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.
// 当我们通过 call 和 apply 来this的指向时,不传任何参数,则默认为将this指向修改为 windows
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.
// 有参数时,this 指向第一个参数:将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.
// 当需要传递参数时,call可以直接写多个参数,apply需要用数组方式传递:
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.
1831

被折叠的 条评论
为什么被折叠?



