javascript - Accessing object properties from object itself -
javascript - Accessing object properties from object itself -
i'm having little problem learning object-oriented javascript. have 2 classes called cosmos
, background
, cosmos
looks this:
// js/cosmos.js function cosmos() { this.background = new background(); // fire game loop this.ticker = setinterval(this.tick, 1000 / 60); } // main game loop cosmos.prototype.tick = function() { console.log(this.background); }
when main game loop ticks, undefined
in console. don't quite understand because this.background
property of cosmos
class, should accessible methods defined in cosmos
class, no?
if go index.html
page's script tag , alter this:
// lift off var cosmos = new cosmos(); console.log(cosmos.background);
it works , background
object gets logged console. can offer explanation , tell me how can access properties of cosmos
within cosmos.tick
?
edit: turns out problem setinterval()
, because if proper object logged console:
function cosmos() { this.background = new background(); // fire game loop //this.ticker = setinterval(this.tick, 1000 / 60); this.tick(); } // main game loop cosmos.prototype.tick = function() { console.log(this.background); }
still don't know best way around it, though.
when function called setinterval
, this
not bound object anymore.
this quick prepare problem:
// js/cosmos.js function cosmos() { var self = this; this.background = new background(); // fire game loop this.ticker = setinterval(function () { self.tick(); }, 1000 / 60); }
by using self
variable, inner function gets access this
.
javascript oop prototype
Comments
Post a Comment