gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:30:37 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com