1

가 나는 CommonJS 모듈이 만들어지지 않습니다 종속성 주입 :자바 스크립트 디자인 패턴 : 아직

// main-module 
module.exports = function() { 
    var foo, 
     someModule = require('other-module')(foo); 

    // A value is given to foo after other-module has been initialised 
    foo = "bar"; 
} 

당신이 볼 수 있듯이,이 요구하는 것은 other-module :

// other-module.js 
module.exports = function (foo) { 
    function example() { 
    console.log(foo); 
    // > "bar" 
    } 
} 

은 내가 example 기능을 싶습니다 내부에 other-module의 내부에 foo 변수가 있음을 알고 있어야합니다. 모듈이 필요한 후에도이 변수가 설정되어 있더라도 main-module 변수입니다.

other-module이 실행될 때 fooundefined이되지 않습니다. 그러나 요점은 내 example 함수가 실행될 때 foobar 값이 주어 졌기 때문입니다.

위의 패턴은 분명히 작동하지 않습니다. 어떤 디자인 패턴을 구현해야합니까?

답변

2

나는 CommonJS와 슈퍼 익숙하지 않은, 그래서이 할 수있는 관용적 인 방법이 될 않을 수도 있지만 대신 변수의 함수를 사용하여 작동합니다 :

// main-module 
module.exports = function() { 
    var foo, 
     someModule = require('other-module')(function() { return foo; }); 

    foo = "bar"; 
} 

// other-module.js 
module.exports = function (fooFn) { 
    function example() { 
    console.log(fooFn()); 
    } 
} 
0

푸 값 (문자열)가 값으로 전달되므로 다른 모듈 내부에는 undefined입니다. 참조로 전달 된 옵션 개체를 사용할 수 있습니다.

var options = {}, 
someModule = require('other-module')(options); 

options.foo = "bar"; 
+0

이것은 작동하지 않는 것 같습니다. –

+0

@OliverJosephAsh는'options = { "foo": "bar"};'를'options.foo = 'bar';'로 변경합니다. –

+1

Thanks @MattBall, 네 말이 맞아. 옵션에 새로운 값을 할당하면 문자열을 값으로 전달할 때와 같은 문제가 발생하므로'options' 참조를 동일하게 유지해야합니다. –