I'm creating an application which will need to have inheritance, but I don't know which way of inheritance definition to choose. I found two ways do define class inheritance, but I don't know the difference between them.
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 inherits from DocBase by setting his prototype to 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 inherits from DocBase by setting his prototype to 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 = [];
Both ways of inheriting works and in both ways I have access to properties from inherited class, but I want to know which way of defining inheritance in javascipt classes is better and why.