javascript - 关于js的继承方式,求解!
本文介绍了javascript - 关于js的继承方式,求解!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
function person(name,age){
this.name = name;
this.age = age;
}
person.prototype.say = function(){
console.log(this.name+":"+this.age);
}
function superman(name,age){
person.call(this,name,age);
}
superman.prototype = new person();
var s = new superman('superman',29);
在书上看到这种继承方式,说很完美,可是我并不觉得啊,因为他的superman.prototype = new person();
这句,会将父类的实例属性添加到子类的原型上啊,虽然person.call(this,name,age);
已经拿到了父类的实例属性,但是感觉这样污染了子类的原型啊,怎么破?
好了,问题解决了,使用寄生组合式继承可以解决这个问题
function object(obj){
function F(){}
F.prototype = obj;
return new F();
}
function inheritProtoType(SuperType,SubType){
var prototype = object(SuperType.prototype);
prototype.constructor = SubType;
SubType.prototype = prototype;
}
function SuperType(){
this.name = 'yuhualingfeng';
this.friends = ['David','Bob','Lucy'];
}
SuperType.prototype.saySuperName = function(){
console.log(this.name);
};
function SubType(){
SuperType.call(this);
this.age = 30;
}
inheritProtoType(SuperType,SubType);
SubType.prototype.saySubName = function(){
console.log(this.name);
};
var subType = new SubType();
解决方案
Object.create(Person.prototype);
这个可以有效解决,不过要注意兼容性
function create(obj) {
if (Object.create) {
return Object.create(obj);
}
function f() {};
f.prototype = obj;
return new f();
}
这篇关于javascript - 关于js的继承方式,求解!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文