Javascript继承与原型

Javascript inheritance with prototype

本文关键字:原型 继承 Javascript      更新时间:2023-09-26

我在谷歌上搜索了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 兼容,可以参考 简单 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');