weird issue in simple class declaration
-
Hi all, I am trying to make a auto blinking div but while trying to achieve using setTimeout its saying " this.off is not a function" in on method I tried two variations. Please help !!!
var Light = function(color) {
this.color = color;
};Light.prototype = {
ref:null,
defColor:'black',
on:function(){
if(this.ref != null){
this.ref.css('background-color',this.color);
window.setTimeout(function(){this.off()}, 5000);
//window.setTimeout(this.off, 5000);
}
},
off:function(){
if(this.ref != null){
this.ref.css('background-color',this.defColor);
window.setTimeout(function(){this.on()}, 5000);
//window.setTimeout(this.on, 5000);
}
}
};var l1;
$(document).ready(function(){
l1 = new Light('red');
l1.ref=$('#mydiv');
l1.on();
}); -
Hi all, I am trying to make a auto blinking div but while trying to achieve using setTimeout its saying " this.off is not a function" in on method I tried two variations. Please help !!!
var Light = function(color) {
this.color = color;
};Light.prototype = {
ref:null,
defColor:'black',
on:function(){
if(this.ref != null){
this.ref.css('background-color',this.color);
window.setTimeout(function(){this.off()}, 5000);
//window.setTimeout(this.off, 5000);
}
},
off:function(){
if(this.ref != null){
this.ref.css('background-color',this.defColor);
window.setTimeout(function(){this.on()}, 5000);
//window.setTimeout(this.on, 5000);
}
}
};var l1;
$(document).ready(function(){
l1 = new Light('red');
l1.ref=$('#mydiv');
l1.on();
});When the anonymous function you've passed to
window.setTimeout
is called,this
will be pointing to the global scope, rather than the specific object instance that calledsetTimeout
. This is one of the confusing quirks of javascript code. There are several possible solutions in the answers to this SO question[^]. For example:-
Save the outer
this
reference:var me = this;
window.setTimeout(function(){me.on()}, 5000); -
For modern browsers, use the built-in
bind
function[^]:window.setTimeout(this.on.bind(this), 5000);
-
Use jQuery's
proxy
method[^]:window.setTimeout($.proxy(this.on, this), 5000);
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
-