oop - JavaScript OO issue when accessing instance methods -
i've used few tutorials on oop in javascript. seemed go well, until met following...
result of expression 'this.prepareframe' [undefined] not function.
ok. i'm using prototype
, make use of this
keyword.
see app.js
page here...
// plain "main" function called html page, <script>main()</script>. works nicely: function main() { engine = new abstractengine(); engine.init(); } // next creates new instance of abstractengine class. seems work far: function abstractengine() {} // init() method called defined afterwards: abstractengine.prototype.init = function() { this.initloop(); } // remark: i'm using "this", , according debugger, "this" refers abstractengine made instance of. // next, define initloop method: abstractengine.prototype.initloop = function() { setinterval(this.tick, 1000 / 30); } // fine, works fine far. define "tick" method: abstractengine.prototype.tick = function() { this.prepareframe(); this.update(); } // ok, we're in trouble. error message output console , don't understand why... prepareframe() , update() methods defined right afterwards: abstractengine.prototype.update = function() { console.log('updating!'); } abstractengine.prototype.prepareframe = function() { console.log('preparing frame'); } // read code twice, didn't find beginner's mistakes typo or whatever. well, cosnider i'm beginner
this:
setinterval(this.tick, 1000 / 30);
should be:
var = this; setinterval(function () { that.tick(); }, 1000 / 30);
or alternately:
setinterval(this.tick.bind(this), 1000 / 30);
explanation: when pass this.tick
, same doing following:
var temp = this.tick; setinterval(temp, 1000 / 30);
but now, when temp
called, javascript doesn't know this
pointer should be; information gets lost, , ends getting bound global object (window
), or null
if in strict mode.
so need somehow ensure this.tick
called method appropriate this
pointer. there 2 ways this:
- by wrapping in closure captures
var = this
, can callthat.tick
method on originalthis
pointer. - or
bind()
ingthis.tick
functionthis
, ensure called method appropriatethis
every time: in other words,var temp = this.tick.bind(this)
,setinterval(temp, 1000 / 30)
.
note bind
not available in older browsers (notably ie <= 8 , safaris far , including 5.1), in case you'd need es5-shim.
Comments
Post a Comment