2

私は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();
    }
  };
};
4

3 に答える 3

2

コードを使用して、この例を検討してください

var core = {}; // define an object literal
core.modules = {}; // define modules property as an object

var wot= 'Muhahaha!';

core.modules.example_module = function(sandbox){

  console.log('wot from creator ==', wot);

  return {
    init: function() {
       console.log('wot from init ==', wot);

    }
  }
}

// logs wot from creator == Muhahaha! to the console    
var anObject = core.modules.example_module(); 

// logs wot from init == Muhahaha! to the console
anObject.init(); 

が実行される時点でwotスコープチェーンのどこかに定義されている限り、これは期待どおりに機能します。core.modules.example_module

トピックから少し外れましたが、関数の範囲に触れました。関数には字句スコープがあります。つまり、(実行ではなく) 定義された時点でスコープを作成し、クロージャーを作成できるようにします。親が戻った後でも、関数がその親スコープへのリンクを保持している場合、クロージャーが作成されます。

于 2010-01-30T23:05:49.760 に答える