JavaScript原型继承

4

我花了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个回答

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/ 为了更好地理解JavaScript中的继承,您可能应该阅读我的博客文章《为何原型继承很重要》

1
给楼主提醒一下——这在现代浏览器(EcmaScript 5标准)上是可用的,但在IE 8等浏览器上不行。 - Will
@Will 嗯,好的,这不是一个大问题。但如果有IE8的解决方案会很好。 - user2820280
@user2820280 只需将以下代码添加到程序开头,它就可以在任何浏览器中运行:if (!Object.create) Object.create = (function (Factory) { return function (prototype) { Factory.prototype = prototype; return new Factory; }; }(function () {})); - Aadit M Shah

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/


1

如果需要兼容IE 7/8,请参考简单的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');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接