我正在创建一个需要继承的应用程序,但我不知道选择哪种继承定义。我找到了两种定义类继承的方法,但我不知道它们之间的区别。
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;
文档通过将其原型设置为Object.create(ns.DocBase.prototype)
来继承自DocBase:
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;
通过将原型设置为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类中定义继承的哪种方式更好,为什么。
答案 0 :(得分:1)
特别是在你提出的情况下,它们是相同的,object.create(ns.DocBase.prototype)
的一个微小优势是它在不执行构造函数的情况下仅继承DocBase.prototype
,因此分配的空间少于使用new (_id和_content未在对象的原型上分配)
这是一个图表来说明差异(某些部分被省略):
注意folder._prototype
中的额外_id和_name。
你的例子中真正的坏习惯是你在原型对象中声明了属性:
ns.DocBase.prototype._id = null;
ns.DocBase.prototype._name = null;
一个不必要的步骤,因为你在文档(和文件夹)构造函数中调用DocBase.call(this)
。