I'm defining a 'class' in JavaScript by means of prototype.
The first time func() runs, it works, but when it's called the second time, through a setTimeout, it fails because this time it has lost the object context, I.E. this doesn't reference the object anymore but now references window.
Is there a way I can overcome this while still using prototype? or do I need instead to use closures to define a 'class'?
function klass(){}
klass.prototype = {
a: function() {
console.log( "Hi" );
},
func: function(){
this.a();
setTimeout( this.func, 100 );
}
};
var x = new klass();
x.func();
You can wrap it in a function:
Use
Function.prototype.bind
, or wrap yoursetTimeout
callback in its own closure:Use
Function.prototype.bind
:From Mozilla Developer Network:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind