JavaScript scope issue (this) -


i have tried organize code in object oriented way (as explained in mdn). in case however, this refers window object. because of error

uncaught typeerror: cannot read property 'render' of undefined

in

this.renderer.render(this.stage);

why refer window object when doesn't on mdn?

var game = game || {};  game.application = function() {     this.renderer = pixi.autodetectrenderer(800, 600,{backgroundcolor : 0x1099bb});     document.getelementbyid("game").appendchild(this.renderer.view);     this.stage = new pixi.container();     requestanimationframe(this.render); }  game.application.prototype.render = function() {     this.renderer.render(this.stage); }  var app = new game.application(); 

lets talk this, context, , functions

a way think it, this refers object on left of . of method calls it.

var someobj = {     name:'someobj',     sayname: function(){         console.log(this.name);     } };  someobj.sayname(); // prints someobj 

functions not methods of object bound window object.

window.name = 'window'; function sayname(){     console.log(this.name); }  sayname(); //prints window 

the above equivalent to

window.sayname(); // window on left of dot, `this` 

when pass method of object parameter, or assign variable, loses original context. below, sayname method of someobj loses someobj context , gains someotherobj.

var someotherobj = {     name:'someotherobj' };  someotherobj.sayname = someobj.sayname;  someotherobj.sayname(); // prints someotherobj 

to around it, can bind context function

var yetanotherobj = {     name: 'yetanotherobj' };  var sayyetanotherobj = sayname.bind(yetanotherobj);  sayyetanotherobj(); // prints yetanotherobj 

or pass anonymous function calls the method on object itself

var onelastobj = function(){     var self = this;     this.somevalue = afunctiontakingacallback(function(){         return self.dosomestuff();     }); } 

something remember when passing functions around parameters passing reference function. function not bound object may method of.


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -