Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 376
Wold Avatar asked Jan 07 '14 05:01

Wold


1 Answers

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).

like image 180
Aks Avatar answered Sep 30 '22 11:09

Aks