Search code examples
javascriptarraysfunction-pointersdom-events

Function object in object array


I am trying to implement a model in Javascript in a object-oriented manner. Say I have object X with bunch of functions. I want to have an object array "in X" that some of its fields point to some functions in X. Here is the example of what I tried:

function X(){

this.open = function(e){...};
this.run = function(e){...};
this.close = function(e){...};
//...

this.STATES = {
    1: {name : "opening", applyAction : this.open},
    2: {name : "runing", applyAction : this.run},
    3: {name : "closing", applyAction : this.close},
    //...
};

this.currentState = this.STATES[1];

//...

this.update = function(e){
    //...
    currentState.applyAction(e);
    //...
}

However this approach does not work as expected. I cant figure out what is wrong, also if you have alternative way of doing the same thing I would truly appreciate it.


Solution

  • This won't work because 'this' inside of the following code points to the literal object you're defining, not the intended 'this':

    this.STATES = {
        1: {name : "opening", applyAction : this.open},
        2: {name : "runing", applyAction : this.run},
        3: {name : "closing", applyAction : this.close},
        //...
    };
    

    Try

    function X() {
        var self = this;
    
        this.open = function() {
            // ...
        }
    
        this.STATES = {
            1: {name: "opening", applyAction: self.open},
            ...
    

    I'd also read up about Javascript scoping.