2015-02-06 14 views
-1

當我使用具有兩個不同參數的模塊時,我得到了一個模塊的兩個實例。如何使它成爲單一實例?在nodejs中如何讓具有不同參數的構造函數的模塊的單個實例?

// module.js 
 

 
module.exports = function(declared){ 
 
\t var count = { 
 
\t \t total : 0 
 
\t } 
 
\t var definedVariable = declared; 
 
\t function increment(){ 
 
\t \t count.total++; 
 
\t \t return { 
 
\t \t \t defined : definedVariable, 
 
\t \t \t count : count.total 
 
\t \t } 
 
\t } 
 
\t return { 
 
\t \t increment : increment 
 
\t } 
 
}

// app.js 
 

 
var express = require('express'); 
 
var bodyparser = require('body-parser'); 
 

 
var mod1 = require('./module.js')(); 
 
var mod2 = require('./module.js')('defined now'); 
 

 
app = express(); 
 
app.use(bodyparser.urlencoded({ extended: false })) 
 
app.use(bodyparser.json()); 
 
app.route('/').get(function(req, res, next) { 
 
    var cnt1 = mod1.increment(); 
 
    res.json(cnt1); 
 
}); 
 
app.route('/defined').get(function(req,res,next){ \t 
 
\t var cnt2 = mod2.increment(); 
 
    res.json(cnt2); 
 
}); 
 
app.listen(8000, function(){ 
 
\t console.log('listening 8000'); 
 
})

當我運行http://localhost:8000http://localhost:8000/defined,我得到不同支數和不同的實例。如何讓他們指向單個實例?

+0

@unobf我不同意。這個問題已被清楚地說明,並且相關的代碼被分享。也許它可能會被略微改寫,但總的來說,乍一看這個問題是可以回答的。僅僅因爲海報可能沒有把握範圍和封閉的概念並不能使他的問題變得不好。告訴人們「離開並學習東西」並不具有建設性。 – 2015-02-06 18:11:56

回答

2

更新您的module.js申報count外的導出函數

// module.js 
var count = { 
    total : 0 
} 
module.exports = function(declared){ 
    var definedVariable = declared; 
    function increment(){ 
     count.total++; 
     return { 
      defined : definedVariable, 
      count : count.total 
     } 
    } 
    return { 
     increment : increment 
    } 
} 

的當count是函數體中時,它會重新聲明每次你從模塊外部調用該函數的時間。

0

Module.js是一個單例。但你不是這樣對待它的。您需要在模塊內部創建變量,然後導出要使用的方法,並在用作閉包時增加計數並設置definedVariable。

// module.js 
var count = { 
     total : 0 
    }, 
    definedVariable = declared; 

module.exports = function(declared){ 
    function increment(){ 
     count.total++; 
     return { 
      defined : definedVariable, 
      count : count.total 
     } 
    } 
    return { 
     increment : increment() 
    } 
} 

現在,在您的服務器

//server.js 

var mod = require('./module.js'); 

var mod1 = mod(); 
var mod2 = mod('defined now'); 
相關問題