javascript - 關於js的繼承方式,求解!

WBOY
發布: 2016-09-21 14:13:02
原創
822 人瀏覽過

<code>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);
</code>
登入後複製
登入後複製

在書上看到這種繼承方式,說很完美,可是我並不覺得啊,因為他的superman.prototype = new person();這句,會將父類的實例屬性加到子類的原型上啊,雖然person.call(this,name,age);已經拿到了父類的實例屬性,但是感覺這樣污染了子類的原型啊,怎麼破?

好了,問題解決了,使用寄生組合式繼承可以解決這個問題

<code>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();
</code>
登入後複製
登入後複製

回覆內容:

<code>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);
</code>
登入後複製
登入後複製

在書上看到這種繼承方式,說很完美,可是我並不覺得啊,因為他的superman.prototype = new person();這句,會將父類的實例屬性加到子類的原型上啊,雖然person.call(this,name,age);已經拿到了父類的實例屬性,但是感覺這樣污染了子類的原型啊,怎麼破?

好了,問題解決了,使用寄生組合式繼承可以解決這個問題

<code>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();
</code>
登入後複製
登入後複製

Object.create(Person.prototype);

這個可以有效解決,不過要注意相容性

<code>function create(obj) {
    if (Object.create) {
        return Object.create(obj);
    }

    function f() {};
    f.prototype = obj;
    return new f();
}</code>
登入後複製

繼承 person.prototype

繼承而不是污染

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!