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));

或使用Bindsmutator(在 Mootools 中提供更多,感谢@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)并实现 Options mutator。

此外,正如您在每条评论中所指出的那样,var self = this;这非常方便且易读。

于 2013-02-13T16:58:40.680 回答