私はjavascriptフレームワークに取り組んでいます。次のような独立したスクリプトがいくつかあります。
core.modules.example_module = function(sandbox){
console.log('wot from constructor ==', wot);
return{
init : function(){
console.log('wot from init ==', wot);
}
};
};
この関数は別の外部スクリプトから呼び出されます。変数にアクセスできるように、この関数に変数を渡そうとしていますwithout using the this keyword.
上記の例では、wot が未定義であるというエラーが発生します。
関数を匿名関数でラップし、そこで変数を宣言すると、期待される望ましい結果が得られます
(function(){
var wot = 'omg';
core.modules.example_module = function(sandbox){
console.log('wot from creator ==', wot);
return{
init : function(){
console.log('wot from init ==', wot);
}
};
};
})();
私がやろうとしているのは、変数をスコープチェーンのさらに上に宣言して、2番目の例のように this キーワードを使用せずにモジュールでアクセスできるようにすることです。関数の宣言時に関数の実行範囲が封印されているように見えるので、これが可能だとは思いません。
update
どこで wot を定義しようとしているのかを明確にするために。別のJavaScriptファイルには、このような登録モジュール関数を呼び出すオブジェクトがあります
core = function(){
var module_data = Array();
return{
registerModule(){
var wot = "this is the wot value";
module_data['example_module'] = core.modules.example_module();
}
};
};