Accessing the properties of the 'this' object inside each loop

What's the best way to access testval and testoption inside a foreach loop? This is a mootools project.

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 this by adding bind (this) to the array, but is that the way?

+3


source to share


2 answers


In cases where I need to refer to multiple instance variables from a function that makes a this

reference to something else, I often use it var self = this;

before. I find he reads a lot better than tying things all over the place; self

becomes explicit to reference an instance.



+3


source


yes, the mootools way to do this is to bind your functions with

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

      

or using a mutant Binds

(available in Mootools More, thanks @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);
 }
});

      

I moved your each (and not forEach as said in the comments) inside initialize (), since I'm not sure if the code inside the object descriptor class works ... Also you can use the passed parameters to initialize with this.setOptions(options)

and implement the Options mutator.

Also, as noted in every comment, you have var self = this;

one that is very easy to read and readable.

+2


source







All Articles