Question

I'm trying to pass an "Options"-Object to the constructor of another object. Options have enumerations which I try to read in another file.

js/mainApp.js:

square = new World(20, 20, null, 0);

var opts = new Options(MODE.SINGLE, REGION.MIDDLE_EAST);
world = new World(0, 0, "img/whatever.png", opts);

js/options.js :

var MODE = {
    SINGLE : 1,
    MULTI  : 2
};

var REGION = {
    MIDDLE_EAST : { xTranslate : -2300, yTranslate: -700, scale : 1.2}
};

function Options(MODE, REGION) {
    this.mode = MODE;
    this.region = REGION;
}

Now in the World constructor I'm getting the error "opts.region is undefined" for the second alert. For some reason the first alert shows the expected "{ xTranslate : -2300, yTranslate: -700, scale : 1.2}"

js/options.js:

var World = ExtendingSomething.extend(
{
    initialize: function(x, y, imageURL, opts) {
        alert (JSON.stringify(opts.region));
        alert (JSON.stringify(opts.region.scale));
        ...
    }
}
);

Edit: I added few information

I don't understand why I'm getting this error is undefined while it works in in this jsfiddle (thanks for creating to Thomas C. G. de Vilhena).

Maybe it's a problem that I'm using different files? still: Why is there no problem with the call opts.region, but as soon as I'm calling opts.region.scale the error opts.region is undefined appears(not opts.region.scale!).

<script type="text/javascript" src="js/mainApp.js"></script>
<script type="text/javascript" src="js/options.js"></script>
<script type="text/javascript" src="js/world.js"></script>

Edit: I needed to add another line of code to understand the problem

Was it helpful?

Solution

The problem is the constructor call with wrong parameters. There should be some kind of type check, otherwise it gives a TypeError.

remove any wrong call to constructor or add a check

square = new World(20, 20, null, 0);

OTHER TIPS

Script files should be loaded in below order.

<script type="text/javascript" src="js/options.js"></script>
<script type="text/javascript" src="js/world.js"></script>
<script type="text/javascript" src="js/mainApp.js"></script>

It seems we are using objects even before they are being loaded.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top