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.

没有正确的解决方案

其他提示

Particularly in the case you presented, they are pretty the same, a tiny advantage of object.create(ns.DocBase.prototype) is that it does inherit only DocBase.prototype without executing the constructor, so there are less space allocated than using new (_id and _content not allocated on the prototype of the objects).
Here's a graph to illustrate the difference (some parts are omitted):

enter image description here

notice the extra _id and _name in folder._prototype.

the real bad practice in your example is that you re declared properties in prototype object:

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

an unnecessary step since you are are calling DocBase.call(this) in the document (and folder) constructor.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top