Skip to content Skip to sidebar Skip to footer

Javascript Inheritance And Losing The Context Of 'this'

I am using John Resig's Simple JavaScript Inheritance and have run into an issue where I am losing what 'this' refers to. Using this code: var Runner = Class.extend({ init: funct

Solution 1:

The problem is when you pass this.update to the setInterval function. In Javascript, the "this" depends on wether you call the function using dot notation, and functions will not remember where they came from if you pass them as callbacks or store them in a variable.

You can either add a wrapper function

var that = this;
setTimeout(function(){ that.update() }, this.perios*1000)

or you can use the bind method if its available in your browser (or you can use the similar function in Prototype).

setTimeout(this.update.bind(this), this.period*1000)

Solution 2:

When you pass this.update to setInterval you lose the context. The simplest solution is to do

var that = this;
this.interval = setInterval(function() { that.update() }, this.period * 1000);

Solution 3:

this.interval = setInterval(this.update, this.period * 1000);

When setTimeout calls a function it calls it in the global scope (it sets this to window).

You need to pass a function that calls this.update.

var self = this;
this.interval = setInterval(function(){
    self.update();
}, this.period * 1000);

Post a Comment for "Javascript Inheritance And Losing The Context Of 'this'"