簡體   English   中英

Javascript繼承原型

[英]Javascript inheritance with prototype

我用谷歌搜索了1個小時,但找不到一個好的答案。 所以這是我的問題:我怎樣才能繼承一個帶有原型的類?

我目前有這個解決方案: http//jsfiddle.net/RdxYN/2/

function BaseContent(a, b) {
    this.propertyA = 'propertyA';
    this.a = a;
    this.b = b;
    alert('x');
}

BaseContent.prototype.funcA = function () {
    alert(this.a + ', ' + this.b);
    alert(this.propertyA);
};

function ContentA(a, b) {
    BaseContent.call(this, a, b);
    this.funcA();
}

ContentA.prototype = new BaseContent;
ContentA.prototype.constructor = ContentA;
ContentA.prototype.parent = BaseContent.prototype;

var Content = new ContentA('c', 'd');

唯一的問題是,BaseContent是否執行了兩次。 我不希望這樣。 有更好的解決方案還是修復?

在JavaScript中實現繼承的新方法是使用Object.create ,如下所示:

function BaseContent(a, b) {
    this.propertyA = 'propertyA';
    this.a = a;
    this.b = b;
    alert('x');
}

BaseContent.prototype.funcA = function () {
    alert(this.a + ', ' + this.b);
    alert(this.propertyA);
};

function ContentA(a, b) {
    BaseContent.call(this, a, b);
    this.funcA();
}

ContentA.prototype = Object.create(BaseContent.prototype);
ContentA.prototype.constructor = ContentA;
ContentA.prototype.parent = BaseContent.prototype;

var Content = new ContentA('c', 'd');

看演示: http//jsfiddle.net/RdxYN/7/

您應該閱讀我關於為什么原型繼承事項的博客文章,以便更深入地了解JavaScript中的繼承。

我的建議是將其設置得更像這樣

function BaseContent(a, b) {
    this.propertyA = 'propertyA';
    this.a = a;
    this.b = b;
    alert('x');
}

BaseContent.prototype = {
    funcA: function () {
        alert(this.a + ', ' + this.b);
        alert(this.propertyA);
    }
};

function ContentA(a, b) {
    BaseContent.call(this, a, b);
    this.funcA();
}

ContentA.prototype = BaseContent.prototype;
ContentA.prototype.constructor = ContentA;

var Content = new ContentA('c', 'd');

這里的例子是JSFiddle http://jsfiddle.net/LD8PX/

對於IE 7/8兼容,您可以參考Simple javascript繼承

請參閱jsfiddle: http//jsfiddle.net/rHUFD/

var BaseContent = Class.extend({
    init: function (a, b) {
        this.a = a;
        this.b = b;
        this.propertyA = 'propertyA';
        alert('x');
    },
    funcA: function () {
        alert(this.a + ', ' + this.b);
        alert(this.propertyA);
    }
}); 

var ContentA = BaseContent.extend({
    init: function (a, b) {
        this._super(a, b);
        this.funcA();
    }
}); 

var Content = new ContentA('c', 'd');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM