在每个循环中访问“this”对象属性

时间:2013-02-13 16:32:54

标签: javascript mootools

在foreach循环中访问 testval testoption 的最佳方法是什么?这是一个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)来修复它,但这是要走的路吗?

2 个答案:

答案 0 :(得分:3)

如果我需要从使this引用其他内容的函数中引用一些实例变量,我以前经常使用var self = this;。我发现它比在整个地方绑定东西要好得多; self变得明确清楚地引用实例。

答案 1 :(得分:2)

是的,mootools这样做的方法是用

绑定你的函数
this.options.testarray.each(function(el) { 
  console.log(this.testval);
  console.log(this.options.testoption);
}.bind(this));

或使用Binds mutator(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)初始化并实现Options mutator。

此外,正如每篇评论中所述,var self = this;非常方便且可读。