我試圖做一些瀏覽器和nodejs服務器之間共享的js代碼。要做到這一點,我只是使用這些做法:http://caolanmcmahon.com/posts/writing_for_node_and_the_browser/Nodejs引用module.exports
問題是當我想導出一個函數,而不是一個對象。在節點,你可以這樣做:
var Constructor = function(){/*code*/};
module.exports = Constructor;
,以便需要時使用,你可以這樣做:
var Constructor = require('module.js');
var oInstance = new Constructor();
問題是,當我嘗試引用module.exports模塊和使用對象該引用用我的函數覆蓋它。在模塊中它將是:
var Constructor = function(){/*code*/};
var reference = module.exports;
reference = Constructor;
爲什麼這不起作用?我不想使用簡單的解決方案在乾淨的代碼中插入一個if,但是我想明白爲什麼它是非法的,即使引用=== module.exports是真的。
感謝