3

foreachループ内のtestvaltestoptionにアクセスするための最良の方法は何ですか?これはmootoolsドラフトです。

var some = new Class({
   options: { testarray: [1,2,3], testoption: 6 },       
   initialize: function(options) {
      this.testval = '123';
      this.options.testarray.each(function(el) { 
         console.log(this.testval);
         console.log(this.options.testoption);
      });
    } 
});

更新: 配列にbind(this)を追加することで修正できますが、それで解決できますか?

4

2 に答える 2

3

直前thisによく使用する他の何かを参照する関数から、いくつかのインスタンス変数を参照する必要がある場合。var self = this;いたるところに物を縛るよりもずっと読みやすいと思います。インスタンスを参照するselfことが明示的に明確になります。

于 2013-02-13T16:38:25.067 に答える
2

はい、これを行うためのmootoolsの方法は、関数を次のいずれかにバインドすることです。

this.options.testarray.each(function(el) { 
  console.log(this.testval);
  console.log(this.options.testoption);
}.bind(this));

またはBindsミューテーターを使用して(Mootools Moreで利用可能、@ Dimitar Christoffに感謝)

var some = new Class({
 options: { testarray: [1,2,3], testoption: 6 },
 Implements: Optons,
 Binds: ['logOption'],
 initialize: function(options) {
   this.testval = '123';
   this.setOptions(options);
   this.options.testarray.each(this.logOptions);
 },
 logOptions : function(value, index, array) {
   // I don't really see the point, but here you are, this code will be executed
   // three times, with (1, 0, [1,2,3]), (2, 1, [1,2,3]) and (3, 2, [1,2,3])
   console.log(value, index, array);
   console.log(this.testval);
   console.log(this.options.testoption);
 }
});

クラス記述子オブジェクトミル内のコードが機能するかどうかわからないため、initialize()内でそれぞれ(コメントで述べたようにforEachではなく)を移動しました...また、初期化で渡されたオプションを使用することもできますthis.setOptions(options)オプションミューテータを実装します。

また、あなたが持っているすべてのコメントに記載されているように、var self = this;それは非常に便利で読みやすいです。

于 2013-02-13T16:58:40.680 に答える