简体   繁体   English

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

[英]Accessing 'this' object properties inside each loop

Whats the best way to access testval and testoption inside the foreach loop? 什么是在foreach循环中访问testvaltestoption的最佳方法? This is a mootools draft. 这是一个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);
      });
    } 
});

UPDATE: I can fix it by adding bind(this) on the array, but is that the way to go? 更新:我可以通过在数组上添加bind(this)来修复它,但这是要走的路吗?

In cases where I need to reference a number of instance variables from a function that makes this refer to something else I often use var self = this; 在我需要从一个功能,使得引用了一些实例变量的情况下, this是指别的我经常用的东西var self = this; just before. 就在此之前。 I find it reads a lot better than binding things all over the place; 我发现它比在整个地方绑定东西要好得多; the self becomes explicitly clear to refer to the instance. self变得明确清楚地引用实例。

yes, the mootools way to do this is to bind your functions either with 是的,mootools这样做的方法是用你的函数绑定

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

or by using the Binds mutator (available in Mootools More, thanks @Dimitar Christoff) 或通过使用Binds突变(在Mootools的可用的更多,由于@Dimitar克里斯托夫)

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

I moved your each (and not forEach, as said in the comments) inside the initialize(), since I'm not sure code inside the class descriptor object mill work... Also you might want to use the passed options in initialize with this.setOptions(options) and implementing the Options mutator. 我在initialize()中移动了你的每个(而不是forEach,如注释中所述),因为我不确定类描述符对象中的代码是否工作...你也可能想在初始化时使用传递的选项this.setOptions(options)和实现Options mutator。

Also, as noted in every comment you have var self = this; 另外,如每条评论所述,你有var self = this; which is very convenient AND readable. 这非常方便和可读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM