一、call
方法
基本用法
function test() {
console.log('hello world');
}
test(); // hello world
test.call(); // hello world
// test() ==> test.call()
其实就是借用别人的方法,来实现自己的功能
function Person(name, age) {
// this == obj
this.name = name;
this.age = age;
}
var obj = {
};
var person = new Person();
Person.call(obj, 'mary', 18); // 让 obj 也拥有构造函数的方法
call
的根本作用就是改变this
指向,第一个参数就是this
的指向
小案例
function Student(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
function Color(red, blue, pink) {
this.red = red;
this.blue = blue;
this.pink = pink;
}
function Model(height, width, len) {
this.height = height;
this.width = width;
this.len = len;
}
function Car(name, age, sex, red, blue, pink, height, width, len) {
// var this = {
//
// };
Student.call(this, name, age, sex);
Color.call(this, red, blue, pink);
Model.call(this, height, width, len);
}
var car = new Car('mary', 18, 'female', 'red', 'blue', 'pink', 175, 75, 175);
二、apply
方法
function Student(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
function Color(red, blue, pink) {
this.red = red;
this.blue = blue;
this.pink = pink;
}
function Model(height, width, len) {
this.height = height;
this.width = width;
this.len = len;
}
function Car(name, age, sex, red, blue, pink, height, width, len) {
// var this = {
//
// };
Student.apply(this, [name, age, sex]);
Color.apply(this, [red, blue, pink]);
Model.call(this, height, width, len);
}
var car = new Car('mary', 18, 'female', 'red', 'blue', 'pink', 175, 75, 175);
call
需要把实参按照形参的个数传进去apply
需要传一个arguments
实参列表
[].slice.call(arguments) -- 能将具有 length 属性的对象转换为数组
三、总结
call
/apply
都是改变this
指向,区别就是传参列表不同