나는 Dominic이 제안한 솔루션이 가장 좋은 솔루션이라는 것을 알았지 만 여전히 "const"선언의 한 가지 특징을 놓치고있다. "const"키워드를 사용하여 JS에서 상수를 선언하면 런타임이 아니라 구문 분석시 상수가 있는지 확인합니다. 따라서 코드 후반부에 상수 이름을 잘못 입력하면 node.js 프로그램을 시작하려고 할 때 오류가 발생합니다. 철자가 틀린 철자 검사보다 훨씬 좋습니다.
Dominic이 제안한 것처럼 define () 함수를 사용하여 상수를 정의하면, 철자가 틀린 경우 오류가 발생하지 않으며 철자가 틀린 상수의 값이 정의되지 않아 두통을 유발할 수 있습니다.
그러나 이것이 우리가 얻을 수있는 최선이라고 생각합니다.
또한 constans.js에서 Dominic의 기능이 개선되었습니다.
global.define = function ( name, value, exportsObject )
{
if ( !exportsObject )
{
if ( exports.exportsObject )
exportsObject = exports.exportsObject;
else
exportsObject = exports;
}
Object.defineProperty( exportsObject, name, {
'value': value,
'enumerable': true,
'writable': false,
});
}
exports.exportObject = null;
이 방법으로 다른 모듈에서 define () 함수를 사용할 수 있으며 constants.js 모듈 내부의 상수와 함수를 호출 한 모듈 내부의 상수를 정의 할 수 있습니다. 그런 다음 script 상수에 두 가지 방법으로 모듈 상수 선언을 수행 할 수 있습니다.
먼저:
require( './constants.js' );
define( 'SOME_LOCAL_CONSTANT', "const value 1", this ); // constant in script.js
define( 'SOME_OTHER_LOCAL_CONSTANT', "const value 2", this ); // constant in script.js
define( 'CONSTANT_IN_CONSTANTS_MODULE', "const value x" ); // this is a constant in constants.js module
둘째:
constants = require( './constants.js' );
// More convenient for setting a lot of constants inside the module
constants.exportsObject = this;
define( 'SOME_CONSTANT', "const value 1" ); // constant in script.js
define( 'SOME_OTHER_CONSTANT', "const value 2" ); // constant in script.js
또한 define () 함수를 상수 모듈에서만 호출하려면 (전역 객체를 팽창시키지 말고) constants.js에서 다음과 같이 정의하십시오.
exports.define = function ( name, value, exportsObject )
script.js에서 다음과 같이 사용하십시오.
constants.define( 'SOME_CONSTANT', "const value 1" );
exports. 그것에 대해 어색한 것은 무엇입니까?