두 개의 다른 매개 변수로 모듈을 사용할 때 두 개의 모듈 인스턴스가 생성됩니다. 그것을 하나의 인스턴스로 만드는 방법? nodejs에서 다른 매개 변수로 생성자를 갖는 모듈의 단일 인스턴스를 갖는 방법은 무엇입니까?
내가 http://localhost:8000 및 http://localhost:8000/defined을 실행
// 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');
})
// 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 }
}
@unobf 서버에서 이제
. 질문은 명확하게 설명되었고 관련 코드가 공유되었습니다. 어쩌면 그것은 약간 어긋나게 될 수도 있었지만 전반적으로 그 질문은 언뜻보기에 답할 수있었습니다. 포스터가 범위와 클로저의 개념을 파악하지 못해서 자신의 질문을 나쁘게 만들지 않기 때문입니다. 사람들이 "떠나서 뭔가를 배우라고"말하면 건설적이지 않습니다. –