Open b60413 opened 8 years ago
require 進來的的東西是個 singleton,然後做了 prototype 繼承所以共用同一個物件
https://github.com/nodejs/node/blob/master/lib/util.js#L896:
exports.inherits = function(ctor, superCtor) {
if (ctor === undefined || ctor === null)
throw new TypeError('The constructor to "inherits" must not be ' +
'null or undefined');
if (superCtor === undefined || superCtor === null)
throw new TypeError('The super constructor to "inherits" must not ' +
'be null or undefined');
if (superCtor.prototype === undefined)
throw new TypeError('The super constructor to "inherits" must ' +
'have a prototype');
ctor.super_ = superCtor;
Object.setPrototypeOf(ctor.prototype, superCtor.prototype);
};
可以去了解一下 prototype 繼承跟一般 class 繼承差在哪
js 實作繼承的招數太多,有七八種以上,可參考 http://shichuan.github.io/javascript-patterns/#code-reuse-patterns
甚至用 plain object 都可以做到大部份繼承想要做到的事
目的
最近初學node.js, 想要自己嘗試寫一個Map module讓其他module去繼承, 但是require module的cache機制導致inherits的module共用了同一個map, 請問應該如何修改才有辦法讓各module有自己的map?
使用的工具
ubuntu 12.04 node.js 4.4.3
操作流程
node server.js
遇到的問題
目的已詳述
嘗試過的解法
應該是架構問題, 完全不知道該從何處下手 (想過用不同的路徑載入Map Module, 但就捨棄了module cache的機制)
程式碼
-----server.js-----
-----map.js-----
-----Player_list_lib.js / Monster_list_lib.js-----
輸出
[ '1', '2', '3' ] [ '1', '2', '3' ]