1、call和apply的作用:改变this的指向。
2、call和apply的区别:传的参数形式不同。call是把实参按照形参的个数传进去,而apply只能传一个实参,且该实参是一个数组。
function test() {}
test();
// --->正常我们写的执行函数是test(),实际在机器内部执行是test.call();
function Car(color, height) {
//没有new的时候,this指的是window
//由于使用call/apply,这里的this指向了obj,可以看成 this == obj;
this.color = color;
this.height = height;
}
var obj = {};
//call的写法,call的第一个参数是改变this的指向,在这里,this指的是obj,第二个参数是对应函数执行的第一个形参,第三个参数是对应函数执行的第二个形参
//Car.call(obj, 'red', 490);
//apply的写法
Car.apply(obj,['red',490]);
// --->打印obj,可以看到obj中有color和height属性
//借用别人的函数,实现自己的功能
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
function Student(name, age, sex, tel) {
//当new一个对象时,会隐式地产生: var this = {};
Person.call(this, name, age, sex);//这里的this是指上面隐式产生的this对象
this.tel = tel;
}
var student = new Student('yota', 18, 'female', 1263);