Apply和Call的作用就是继承,类似于PHP的extends。两者作用是一样的,但是用法上还是有点区别。talk is cheap show code~
Apply :
//apply
(function() {
function person(name, age) {
console.log(this) //三次调用person,上下文分别为:window, student, teacher
if (!name) return;
this.prototype.name = name;
this.prototype.age = age;
}
person();
function student(name, age) {
//person.apply(this, name, age); --second argument to Function.prototype.apply must be an array
person.apply(student, [name, age]);
console.log('My Name Is ' + this.name + ' ,Age Is ' + this.age);
}
function teacher(name, age, college) {
person.apply(teacher, arguments);
console.log('My Name Is ' + this.name + ' ,Age Is ' + this.age);
}
var student = new student('gaozhen', '22');
var teacher = new teacher('qianwen', '23');
})()
Call :
//call
(function() {
function person(name, age) {
this.prototype.name = name;
this.prototype.age = age;
console.log(this) //上下文分别为:student、teacher
}
function student(name, age) {
person.call(student, name, age);
console.log('This Student Name Is ' + this.name + ' ,Age Is ' + this.age);
}
function teacher() {
person.call(teacher, arguments);
console.log('This Teacher Name Is ' + this.name + ' ,Age Is ' + this.age);
}
var student = new student('gaozhen', '22');//This Student Name Is gaozhen ,Age Is 22
var teacher = new teacher('qianwen', '23');//This Teacher Name Is [object Arguments] ,Age Is undefined
})()
Apply和Call从用法角度来讲,区别在于apply可以无需指定参数个数,通过auguements来弹性的进行传参,且传入参数必须为Array。而call则必须要指定传参,且传入的参数必须为Object。两者在传入的时候,都会改变继承函数的上下文(如果对象传入为空的话,则为全文)。如person直接执行的话,this输出为window,后续被继承时,分别为student和teacher