Javascript继承原型

时间:2013-09-26 16:10:16

标签: javascript oop inheritance 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是否执行了两次。我不希望这样。有更好的解决方案还是修复方法?

3 个答案:

答案 0 :(得分:4)

在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/

您应该阅读Why Prototypal Inheritance Matters上的博文,以便更深入地了解JavaScript中的继承。

答案 1 :(得分:1)

我的建议是将其设置得更像

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/

的示例

答案 2 :(得分:1)

对于IE 7/8兼容,您可以参考Simple javascript inheritance

请参阅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');