Skip to content Skip to sidebar Skip to footer

Javascript - "this" Pointing To Window Instead Of Object

I'm facing for the first time OOP in JavaScript and all the troubles that comes with it... I have this function/Object/class/whatever which has a method mainLoop() that should disp

Solution 1:

Alter your start function:

start: function(){
        var self = this;
        for(var i = 0; i < this.cols; i++)
            this.drops[i] = 0;
        timer = setInterval(function() {
            self.mainLoop(); 
        }, this.delay);
    }

this was poiting at window because the scope has changed.

Solution 2:

Since JavaScript is prototype-based, maybe (if you haven't already) try doing it following this model:

functionMatrix(config) {

    this.property = config.firstmember;
    this.property2 = config.secondmember;

    returnfunction() { console.log('hello world') };

}

Matrix.prototype = {

    someMethod: function() {
        //do something
    },
    start: function() {
        //console.log('hello world');
    },
    stop: function() {
        //do something
    }

}

var config = {
    firstMember: 'foo',
    secondMember: 'bar'
}

var m = new Matrix(config);

//console output: "hello world"

/*var m = {
    property: 'foo',
    property2: 'bar',
    ____proto___: Matrix: {
            someMethod: function() {
                //do something
            },
            start: function() {
                //console.log('hello world');
            },
            stop: function() {
                //do something
            }
        }

}*/

Also, see the answer to this question regarding setInterval.

setInterval callback functions are members of the Window object; therefore, 'this' refers to the window. You will need to pass in a parameter of the current object to the callback that is inside setInterval. See the link above for more details.

Solution 3:

If you need a reference to the calling object, I'd suggest passing it down as a parameter to the function.

Post a Comment for "Javascript - "this" Pointing To Window Instead Of Object"