1.prototype的方式
//父类
function person(){
this.name= 'xg';
this.sex= 'man';
this.age= '25';
this.show= function(){
return this. name + ',' + this. sex + ',' + this. age ;
}
}
//子类
function man(){
this.feature = ['beard','strong'];
}
man.prototype = new person();
var one = new man();
console.log(one.feature); //['beard','strong']
console.log(one.name); //xg
console.log(one.sex); //man
console.log(one.age); //25
console.log(one.view()); // xg , man , 25
这种方式最简单,只需要让子类的prototype属性值赋值为父类的一个实例就行了,之后就可以直接使用被继承类的方法了。
2.apply的方式
//父类
function person(){
this.name= 'xg';
this.sex= 'man';
this.age= '25';
this.show= function(){
return this. name + ',' + this. sex + ',' + this. age ;
}
}
//子类
function man(){
person.apply(this,[])
this.feature = ['beard','strong'];
}
var one = new man();
console.log(one.feature); //['beard','strong']
console.log(one.name); //xg
console.log(one.sex); //man
console.log(one.age); //25
console.log(one.view()); // xg , man , 25
如果apply参数为空,即没有参数传递,则通过 new Array() 、[] 来传递,null 无效。
但是用apply方法也还是有缺点的,为什么?在js中,我们有个非常重要的运算符就是”instanceof”,该运算符用来比较某个对向是否为某种类型。即(one instanceof person)的值为false。
使用call与apply方法类似,call与apply的不同就是call传的值可以是任意的,而apply传的剩余值必须为数组。
3.call+prototype
//父类
function person(){
this.name= 'xg';
this.sex= 'man';
this.age= '25';
this.show= function(){
return this. name + ',' + this. sex + ',' + this. age ;
}
}
//子类
function man(){
person.call(this,[])
this.feature = ['beard','strong'];
}
man.prototype = new person();
var one = new man();
console.log(one.feature); //['beard','strong']
console.log(one.name); //xg
console.log(one.sex); //man
console.log(one.age); //25
console.log(one.view()); // xg , man , 25
此方法,若person带多参数,调用时需要重复传递参数
最完善的继承方式: