前提call与apply
apply与call都能劫持另外一个对象的方法,继承另外一个对象的属性
apply(obj,[]) call(obj,params)
obj:这个obj对象将替换function中的this对象
apply另外一个参数为数组,call另外一个参数为参数列表,下面就是使用例子
function Person(name,age)
{
this.name=name;
this.age=age;
}
function Student(name,age,grade)
{
//Person.apply(this,[name,age,grade]);
Person.call(this,name,age,grade);
this.grade=grade;
}
//创建一个学生类
var student=new Student("zhangsan",21,"一年级");
//测试
console.log("name:"+student.name+"\n"+"age:"+student.age+"\n"+"grade:"+student.grade);
第一种方式 prototype
基本思想:利用原型让一个引用类型继承另外一个引用类型的属性和方法。
构造函数,原型,实例之间的关系:每个构造函数都有一个原型对象,原型对象包含一个指向构造函数的指针,而实例都包含一个指向原型对象的内部指针。
//父类
function person(){
this.hair = 'black';
this.eye = 'black';
this.skin = 'yellow';
this.view = function(){
return this.hair + ',' + this.eye + ',' + this.skin;
}
}
//子类
function man(){
this.feature = ['beard','strong'];
}
man.prototype = new person();
var one = new man();
console.log(one.feature); //['beard','strong']
console.log(one.hair); //black
console.log(one.eye); //black
console.log(one.skin); //yellow
console.log(one.view()); //black,black,yellow
第二种方式 apply
基本思想:在子类型构造函数的内部调用超类构造函数,通过使用call()和apply()方法可以在新创建的对象上执行构造函数。
//父类
function person(){
this.hair = 'black';
this.eye = 'black';
this.skin = 'yellow';
this.view = function(){
return this.hair + ',' + this.eye + ',' + this.skin;
}
}
//子类
function man(){
// person.apply(this,new Array());
person.apply(this,[]);
this.feature = ['beard','strong'];
}
var one = new man();
console.log(one.feature); //['beard','strong']
console.log(one.hair); //black
console.log(one.eye); //black
console.log(one.skin); //yellow
console.log(one.view()); //black,black,yellow
第三种方式 call + prototype
基本思想:将原型链和借用构造函数的技术组合在一块,从而发挥两者之长的一种继承模式。
//父类
function person(){
this.hair = 'black';
this.eye = 'black';
this.skin = 'yellow';
this.view = function(){
return this.hair + ',' + this.eye + ',' + this.skin;
}
}
//子类
function man(){
// person.apply(this,new Array());
person.call(this,[]);
this.feature = ['beard','strong'];
}
man.prototype = new person();
var one = new man();
console.log(one.feature); //['beard','strong']
console.log(one.hair); //black
console.log(one.eye); //black
console.log(one.skin); //yellow
console.log(one.view()); //black,black,yellow