1

I am writing some javascript that does the following:

  1. The main function creates a "ModelState" instance called "currentState".
  2. The "currentState" object creates a "LabScene" instance called "scene".
  3. The scene then tries to execute a callback to "currentState" passing itself as an argument.
  4. I get the following error:

Uncaught TypeError: Cannot read property 'push' of undefined at ModelState.dirtyListCallback (Test.js:16)

The code is below:

function main(){
    //load state
    var currentState = new ModelState();
}   

function ModelState(){

    this.dirtyList = [];
    //initialize the scene.
    this.scene = new LabScene(this.dirtyListCallback);
}

ModelState.prototype.dirtyListCallback = function(dirtyObject){
    this.dirtyList.push(dirtyObject);
    console.log(this.dirtyList);
};

function LabScene(dirtyListCallback){
    dirtyListCallback(this);
}

I expected the currentState object to store the scene object in the dirtyList array. But that is not happening. This is part of a much larger code base in which child objects are expected to identify themselves as "dirty" (needs to be re-drawn) to their parent. Any help would be appreciated.

BPoy
  • 149
  • 2
  • 10

1 Answers1

2

The scope of this will be (window || global) when you are executing dirtyListCallback inside LabScene.

You need to bind the scope you want to execute the dirtyListCallback method in.

this.scene = new LabScene(this.dirtyListCallback.bind(this));
AvcS
  • 2,143
  • 7
  • 15
  • That worked. Thank you. I guess I need to do some research on .bind(). Not sure I have totally wrapped my head around why it works that way but not the other. – BPoy Apr 19 '18 at 14:32
  • You can refer the linked issue, to understand how "this" works – AvcS Apr 19 '18 at 14:33
  • ooook!!! So basically when you pass a function somewhere else, if the body of that function utilizes the keyword "this", it does not carry with it the original "this". It associates it with whatever "this" context is at its destination. By manually binding it, you send the original context with it. Correct? – BPoy Apr 19 '18 at 15:29
  • yes sir!! You got it :D – AvcS Apr 19 '18 at 15:34