call() / apply()
作用
修改this的指向。
call()
任何方法后都可以加 .call( )
//效果相同
test() ----> test.call()
当 call( ) 括号中有参数时,他会将前面的方法中的所有的this指向都修改为括号中的第一个参数。其余参数作为实参传入。
//使用call()借用别人的函数,完成自己的功能。
function Person(name, age){
//this == obj
this.name = name;
this.age = age
}
var obj = {}
// call的第一个参数代表着修改的this指向。
Person.call(obj,"sada", 100)
//控制台
> obj
< {name: "sada", age: 100}
call()应用举例:
-
借用已存在的Person函数,来完成Student函数中的name,age,sex功能。(注意一但使用了call就相当于把上面的三条语句全拿了过去,不能挑选的拿)
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); this.tel = tel; this.grade = grade; } var student = new Student("hu", 28, "girl", 123123213, 250); console.log(student);
-
function Wheel(wheelSize, style){ this.style = style; this.wheelSize = wheelSize; } function Sit (c, sitColor) { this.c = c; this.sitColor = sitColor; } function Model (height, width, len) { this.height = height; this.width = width; this.len = len; } function Car (wheelSize, style, c, sitColor, height, width, len) { Wheel.call(this, wheelSize, style); Sit.call(this, c, sitColor); Model.call(this, height, width, len); } var car = new Car (200, "big", "s", "red", 11, 222, 33);
apply ( ) 与 call ( ) 的区别
传参列表不同
call 需要把实参按照形参的个数传进去
apply 需要传一个arguments
Sit.apply(this, [wheelSize, style]);
Sit.call(this, c, sitColor);