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();
回複內容:
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();}
繼承 person.prototype
繼承而不是汙染