我正在創建一個需要繼承的應用程序,但我不知道選擇哪種繼承方式。我發現有兩種方法可以定義類繼承,但我不知道它們之間的區別。通過設定他的原型在javascript中繼承類的最佳做法
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 = [];
繼承的作品,並在這兩個兩種方式:
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)
繼承我可以從繼承類訪問屬性的方式,但我想知道在javascipt類中定義繼承的方式更好nd爲什麼。
Prototype是一個共享對象當您將parent的實例(包含實例成員)設置爲此處顯示的child的原型時,可能會發生什麼情況。 http://stackoverflow.com/a/16063711/1641941 – HMR