call和apply的区别
call 和 apply 都是改变this指向,传参方式不同:
call 需要把实参按照形参的个数传进去。
apply 需要传一个arguments。
使用方式:
call(obj, arg1, ...., argN):
function Person(name,age){
this.name = name;
this.age = age;
}
var person = new Person('yyy','456');
console.log(person);
var obj = {}
//Person() ---> Person.call();
Person.call(obj,'xxx',123); //Person函数里面的this为obj
console.log(obj); // {age : 'xxx',age : 123}
apply(obj,[arg1,....,argN ]):
function Person(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
function Student(name, age, sex, tel, grade){
//Person.call(this,name,age,sex);
Person.apply(this,[name,age,sex]);
this.tel = tel;
this.grade = grade;
}
var student = new Student('sunny',123,'male',139,2024);