Kaninepete
Kaninepete

Reputation: 1447

Constructor function. Can't overwrite reference to global variable

I use this constructor to make objects for a game. Right now, the series of images gets overwritten everytime, such that all the objects look the same on screen.

Here's the object in question:

function Box() {
    this.ready = false;
    this.pics = pictures;//[];
    this.state = 0;
    this.x = 0;
    this.y = 0;
    this.w = 1;
    this.h = 1;
    this.fill = "#444";
    this.load = function(array){
        var foo = [];
        pictures = [];
        for(var i = 0; i < array.length; i++){
            pictures.push(loadPic(array[i]));
            foo.push(loadPic(array[i]));
        }
        //this.pics = pictures;
        this.pics = foo;
    }
}

The line

this.pics = foo;

seems to do nothing at all.

Also, if I change the initial value of pics to anything but "pictures" (which is a global variable) the game does not start.

Contex: https://github.com/kaninepete/Javascript-Games/blob/images/MVP.js

Upvotes: 1

Views: 350

Answers (3)

chris.amery
chris.amery

Reputation: 1

Your use of this within a seperate function doesn't point to the object where the variable belongs.

Upvotes: 0

Augustus Kling
Augustus Kling

Reputation: 3333

Initially, you are creating your player and target objects and load their pictures by calling load. Because you are using the object-dot-method syntax, for example player.load to call the functions all references to this should be set as required/expected.

However to start the game, you are calling reset (for example from myDown). Within reset the objects in player and target are replaced with new instances (notice the calls to addRect). The method load is never called on the new instances and thus both are left with the identical pictures (the global pictures as initially set in Box). Because both are sharing the same array, pictures, they end up being painted the same.

General advice: I suggest to get rid of the global variables because their dependencies on each other are not obvious. Then you should call the reset function for initialization instead of doubling the implementation on the global level. Try painting a static picture first before introducing event handlers.

Upvotes: 1

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340903

Try this:

var $this = this;
this.load = function(array){
    //...
    $this.pics = foo;
}

You must be aware that this inside a function is not the same this as in the constructor. In fact the one in load() function points to browser window object.

Instead we define a variable named $this (most people prefer that in pattern) and reference it from inside the function, making it a closure.

Upvotes: 2

Related Questions