Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help understanding JavaScript objects

I am trying to understand objects in javascript. Here is the code:

var fn={};
var canvas;
var ctx;
fn.game=function(width,height,inSide,name){
    this.canvas2=document.getElementById(inSide).innerHTML = "<canvas id="+name+" style='width:"+width+";height:"+height+";'>Your browser does not support the Canvas Element.</canvas>";
    this.canvas=document.getElementById(name);
    this.ctx=this.canvas.getContext("2d");
    document.getElementById(inSide).style.width=width;
    document.getElementById(inSide).style.height=height;
    canvas=document.getElementById(name);
    ctx=this.canvas.getContext("2d");
    this.width=width;
    this.height=height;
    canvas.width=width;
    canvas.height=height;
    this.add={

    };
    this.add.state=function(name){
        this[name]=3;
    };
};


var game=new fn.game(640,480,"game","canvas");

game.addState("play");

when I am referencing this["name"] I am trying to refer this to fn.game, but that dous not work because this references the most local object. Any ideas on how to do this?

like image 824
Andrew Stavast Avatar asked Dec 20 '22 08:12

Andrew Stavast


1 Answers

As you said, it references the most local object, to do what you explained :

...
fn.game=function(width,height,inSide,name){
    var that = this;//expose this of fn.game to this scope
    ...
    this.add={

    };
    this.add.state=function(name){
        that[name]=3;//access this of fn.game
    };
};
like image 191
topheman Avatar answered Jan 03 '23 09:01

topheman