Wold
Wold

Reputation: 972

Javascript: "Undefined" is not an object

I am writing a script that deals with a variable gameRegion like so:

//In the main of the script

var variable= new work();
variable.onCrash(crashHandler,{xPos:650,yPos:300});


// In function work()

var gameRegion;
var onCrashCallback;

this.onCrash = function(crashCallback,fieldSize) {
gameRegion = fieldSize;
onCrashCallback = crashCallback;
};

crashHandler(){
//unimportant
}

this.atBottom = function(ypos) { 
    if(ypos>gameRegion.yPos) //line with the problem
        return true;
    return false;
};

I am getting the console error: TypeError: 'undefined' is not an object (evaluating 'gameRegion.yPos'). Presumably that means I am not properly defining gameRegion or its variable yPos. I've been looking at this code for a while now and I can't seem to find what the problem is.

Hopefully you'll see something that I don't, but if I'm not including necessary code for context, please tell me. Thanks for any help in advance.

Upvotes: 5

Views: 40011

Answers (2)

Aks
Aks

Reputation: 1587

You have to handle 'undefined'. Which can be done in these ways:

typeof(foo) == 'undefined'
typeof foo !== 'undefined'
window.foo !== undefined
'foo' in window

The first three should be equivalent (as long as foo isn't shadowed by a local variable), whereas the last one will return true if the global varible is defined, but not initialized (or explicitly set to undefined).

Upvotes: 9

Elliott Frisch
Elliott Frisch

Reputation: 201507

You can use typeof like so -

return (typeof (gameRegion) !== "undefined" && 
        typeof(gameRegion.yPos) !== "undefined" &&
        ypos > gameRegion.yPos);

Upvotes: 2

Related Questions