2013-03-24 35 views
1

我試圖做一些瀏覽器和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是真的。

感謝

回答

2

它不工作,因爲referencemodule.exports,它指向的對象module.exports點:

module.exports 
       \ 
       -> object 
      /
    reference 

當你一個新的值賦給reference,你只要改什麼reference指向,而不是什麼module.exports指向:

module.exports 
       \ 
       -> object 

reference -> function 

這裏被簡化例如:

var a = 0; 
var b = a; 

現在,如果你設置b = 1,那麼a值仍然會0,因爲你只是分配一個新的價值b。它對a的價值沒有影響。

我想知道爲什麼它是非法的,即使參考=== module.exports是真的

這不是非法,這怎麼JavaScript的(以及大多數其他語言)的工作。 reference === module.exports是正確的,因爲在賦值之前,它們都指向同一個對象。分配後,references指的是與modules.export不同的對象。