0

I am trying to build up a super primitive cue function. Essentially need to repeat an operation n number of times.

var serialCue = {
  init:function(length_of_cue, handler){
    this.length_of_cue = length_of_cue;
    this.handler = handler;
    //this.handler();
    var index = 0;
  },
  monitor: function(){
    console.log(this.index);
    // this.handler();
    // this.index++;
    // if(this.index>=this.length_of_cue){
    //   this.handler();
    // }
  },
  eachIteration: function(callback){
    console.log("yo");
    callback();
  },
  startProcessing: function(){
    for(var count=0;count<this.length_of_cue;count++){
      this.eachIteration(this.monitor);
    }
  }
}

module.exports = Object.create(serialCue);

//IN APP.JS
var cue = require('./serial_cue.js');

cue.init(5,function(){
  console.log("done done and done!");
});

cue.startProcessing();

The output returns "undefined" for the value of the index. I am trying to figure why "this" behaves predictably within all of the methods defined for this object except monitor. Still a little shaky with scopes in JS.

dima
  • 870
  • 8
  • 10
  • index is a local variable in your init() function. You should also look into the .bind() function: this.eachIteration(this.monitor.bind(this)). – nnnnnn Feb 20 '16 at 05:31
  • @nnnnnn but changing it to this.index = 0; produces the same result – dima Feb 20 '16 at 05:35
  • True, because there is a second part to the problem, hence my mention of .bind(). See the answer below. [MDN's `this` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) may also help. – nnnnnn Feb 20 '16 at 05:39

1 Answers1

2

When you call a function as functionName(), rather than as the method of some object, like object.functionName(), its this value will default to undefined in strict mode, and the global object in "sloppy mode".

Two options here are:

Bind the function to this before passing it into your method:

this.eachIteration(this.monitor.bind(this));

Or if you want the callback in eachIteration to always have the current this as its this value, you can use the callback's .call() method:

callback.call(this);


Another issue is that index is a local variable inside your init method and it disappears as soon as init() finishes executing. If you want your object to have an index property, make it a property:
var serialCue = {
    index: 0,
    init:function(length_of_cue, handler){
.....
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Put together a quick gist based on solutions suggested. https://gist.github.com/Digi-D/7de9ad7952c0b07f9d5d thnx! – dima Feb 20 '16 at 17:04