0

Possible Duplicate:
Javascript: Do I need to put this.var for every variable in an object?

I ran into a problem with the following code:

var BuildMiniMap = function(camera, mapSize, width){

    this.camera = camera;
    this.canvas = document.getElementById('gameCanvas');
    this.mapSize = mapSize;
    this.width = width;
    this.height = Math.floor(mapSize[1]/(mapSize[0]/width));

    alert(canvas);
}

var miniMap = new BuildMiniMap(camera, [800, 600], 200);

Running it in a webpage will lead to an error in console:

Uncaught ReferenceError: canvas is not defined

And I have to use this.canvas instead. This only happens with canvas property, but not any other property. Does anyone know the reason and can provide an explanation? Thanks!

Community
  • 1
  • 1
Mr.Teen
  • 591
  • 1
  • 6
  • 17

2 Answers2

1

The other three properties, camera,mapSize and width are all defined as function arguments so are available within the function scope. canvas is not a function argument and is not defined inside the function so it doesn't exist within the scope.

Seain Malkin
  • 2,273
  • 19
  • 20
1

You will need to distinguish between variables and properties. There are only three [local] variables in your constructor function, namely the parameters camera, mapSize, and width.

canvas, height etc. are properties of your instance, which you assign some values to by using the this keyword.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375