关于 call() 和 apply()
用法: A.call(B,x,y....)
让B对象拥有A对象的属性或方法。
(这里面的 x ,y...)用来替代A对象的形参??)
例子:
function person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
this.say = function () {
alert('my name is ' + name);
}
}
function student(name, age, sex, university, major) {
this.name = name;
this.age = age;
this.sex = sex;
this.say = function () {
alert('my name is ' + name);
}
}
function student(name, age, sex, university, major) {
this.name = name;
this.university = university;
this.major = major;
/* person.call(this, name, age, sex); */
this.university = university;
this.major = major;
/* person.call(this, name, age, sex); */
/* 上面是让 student 拥有 person 的 name, age, sex,同时对name, age, sex 重写赋值 */
person.call(this,"TED" ,12, "man");
/* 上面是让 student 拥有 person 的 name, age, sex,同时对name, age, sex 重写赋值为"TED" 12 和"man" */
}
var john = new student('john', 20, 'male', 'MIT', 'webdeveloper');
alert(john.age);
john.say();
var john = new student('john', 20, 'male', 'MIT', 'webdeveloper');
alert(john.age);
john.say();
===============================
注意:这个时候alert(john.name); 输出的是TED,也就是 person.call(this,,"TED" ,12, "man"); 后 调用了person对象中的 this.name 把 student对象中的 this.name 覆盖掉了。
也就是
function student(name, age, sex, university, major) {
this.name = name;
this.university = university;
this.major = major;
this.university = university;
this.major = major;
person.call(this,,"TED" ,12, "man");
/* 可以理解为下面这样表达 */
this.name = name;
this.university = university;
this.major = major;
this.major = major;
this.name = "TED";
this.age = 12;
this.sex = "man";
}
第二个 this.name 覆盖掉了 第一个 this.name
============================
apply() 和 call() 用途差不多, apply()与 call() 的区别就是在于:
call() 传递给函数的参数必须逐个列举出来。
而 apply() 传递参数可以是Array的实例(也就是把要传递的参数放入数组里面),也可以是arguments 对象。
比如:
person.call(this,"TED" ,12, "man");
person.apply(this, ["TED" ,12, "man"]);
person.apply(this, arguments); 《js高级》p116