call和apply的作用与区别
call和apply函数的作用都是改变this指向,this指向也就是更改当前函数的所继承的原型链方法,通过__proto__指向 call和apply函数传入的第一个参数对象的constructor方法,从而达到继承所指向对象的属性和方法的目的。
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
// 当没有参数时,默认将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.
当需要传递参数时,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
下面提供一个例子可以亲自去验证一下
//构造函数应用
function Grade(max, min, average) {
this.max = max;
this.min = min;
this.average = average;
}
function Subject(subjectName,max, min, average) {
Grade.call(this, max, min, average);
this.subjectName = subjectName;
}
var math = new Subject('math', 99, 60, 80);
console.log(math);

浙公网安备 33010602011771号