javascript - javascript中继承类的最佳实践

标签 javascript class inheritance

我正在创建一个需要继承的应用程序,但我不知道选择哪种继承定义方式。我发现有两种定义类继承的方法,但我不知道它们之间的区别。

var ns = {}; // Namespace
ns.DocBase = function (id, name) {
    this._id = id;
    this._name = name;
};
ns.DocBase.prototype.constructor = ns.DocBase;
ns.DocBase.prototype._id = null;
ns.DocBase.prototype._name = null;

Document 继承自 DocBase,将其原型(prototype)设置为 Object.create(ns.DocBase.prototype) :

ns.Document = function (id, name, content) {
    ns.DocBase.call(this, id, name);
    this._content = content;
};

ns.Document.prototype = Object.create(ns.DocBase.prototype);
ns.Document.prototype.constructor = ns.Document;
ns.Document.prototype._content = null;

Folder 继承自 DocBase,将其原型(prototype)设置为 new ns.DocBase()

ns.Folder = function (id, name, childs) {
    ns.DocBase.call(this, id, name);

    if (Array.isArray(childs)) {
        childs.forEach(function (elem) {
            if (elem instanceof ns.Folder) {
                this._folders.push(elem);
            } else if (elem instanceof ns.Document) {
                this._documents.push(elem);
            }
        });
    }
}
ns.Folder.prototype = new ns.DocBase();
ns.Folder.prototype.constructor = ns.Folder;
ns.Folder.prototype._documents = [];
ns.Folder.prototype._folders = [];

两种继承方式都有效,并且通过这两种方式我都可以访问继承类的属性,但我想知道在 javascipt 类中定义继承的哪种方式更好以及为什么。

最佳答案

特别是在您提出的情况下,它们非常相同,object.create(ns.DocBase.prototype) 的一个微小优势是它只继承 DocBase.prototype 不执行构造函数,因此比使用 new 分配的空间更少(_id 和 _content 未在对象的原型(prototype)上分配)。
下面用一张图来说明差异(省略了一些部分):

enter image description here

注意folder._prototype中额外的_id和_name。

您的示例中真正不好的做法是您在原型(prototype)对象中重新声明了属性:

ns.DocBase.prototype._id = null;
ns.DocBase.prototype._name = null;

这是一个不必要的步骤,因为您在文档(和文件夹)构造函数中调用 DocBase.call(this)

关于javascript - javascript中继承类的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22154993/

相关文章:

javascript - 无法使用 jQuery 选择元素

java - 如何从 JRuby 获取 Java 接口(interface)的类型正确的 ruby​​ 实现?

c# - 如何正确继承和隐藏基方法

java - 父类(super class)子类实例化

javascript - Bootstrap Range Slider 限制 handle 范围

JavaScript 不是从外部链接加载的

Python如何在处理完类对象后释放内存?

jquery - 如何用 jquery 中的另一个替换特殊类?

java - 在Java中: Code reuse possible for a chain of method calls up an inheritance hierarchy?

javascript - 访问文本字段的兄弟变量