編集私はあなたの質問に直接答えていないことに気づきました。ごめん!ただし、これがいくつかの代替手法を理解するのに役立つことを願っています。
これは、プロパティや関数を一度追加して、後で上書きできないようにする場合など、私が時々使用する手法です。
var module = new function(){
var modules = {}; //internal module cache
return function(name, module){
//return all modules
if( !name ) return modules;
//return specific module
if( modules[name] ) return modules[name];
//return the module and store it
return modules[name] = module;
}
}
したがって、次のように使用できます。
//will store this since it doesn't exist
module('test', 'foo'); //Since 'test' doesn't exist on the internal 'modules' variable, it sets this property with the value of 'foo'
module('test'); // Since we aren't passing a 2nd parameter, it returns the value of 'test' on the internal 'modules' variable
module('test', 'bar'); //We are attempting to change the value of 'test' to 'bar', but since 'test' already equals 'foo', it returns 'foo' instead.
module(); // { 'test': 'foo' } //Here we aren't passing any parameters, so it just returns the entire internal 'modules' variable.
注目すべき重要なことは、「new function()」を使用していることです。これは割り当て時に行われます。これは、'module' を外部関数ではなく内部関数にしたいためです。しかし、内部の 'var modules' 変数のクロージャを作成するには、外側の関数を割り当て時に実行する必要があります。
また、外部関数も自己実行するように記述できることに注意してください。
var module = function(){
var modules = {};
//other stuff
}();