Can anyone tell me why my ‘showDiv_boo’ is undefined inside the class´s method?
I also can´t access my class´s methods.
Here´s my class ‘Blink’ class with its properties and methods:
function Blink(div) {
this.div = div
}
Blink.prototype.counter = 0
Blink.prototype.showDiv_boo = true
Blink.prototype.showDiv = function() {
this.div.style.visibility = 'visible'
}
Blink.prototype.hideDiv = function() {
this.div.style.visibility = 'hidden'
}
Blink.prototype.startEngine = function() {
if (this.showDiv_boo) {
this.showDiv()
} else if (!this.showDiv_boo) {
this.hideDiv()
}
this.showDiv_boo = !this.showDiv_boo
this.counter++
}
Blink.prototype.startEffect = function() {
this.idEffect = setInterval(this.startEngine, 1000 / 45)
}
So, if I create:
_blink = new Blink(myDiv);
_blink.startEffect();
You can test… the variable ‘showDiv_boo’, is undefined inside the method.
Even, if I set the showDiv_boo inside the method to true, it won´t call my class´s methods showDiv or hideDiv.
Anyone?
Thanks 🙂
You need to:
var selfand call the method viaself.startEngine()function(){ self.startEngine(); }This is because when you just pass
this.startEngineorself.startEngineyou are just passing the function startEngine without specifying whatthisis, which in both cases is supplied by the global conext ofDOMWindow.To give an example…
works to add code to the prototype and if used in the anonymous function will work as expected, but if you just use
Blink.startEngineas the callback it is exactly the same as usingstartEngineonly the second is more obviously wrong because there’s no object it is being called on so you’d expectthisto be whatever is supplied by the context.The other way you could do this without using the anonymous function would be
Which returns a function that will call
startEnginewith the correctthissame as explicitly creating the anonymous function and wrapping the call toself.startEngine()Heres a link to a fiddle to play around with the differences: http://jsfiddle.net/bonza_labs/MdeTF/