Javascript:"未定义"不是对象

Wol*_*old 4 javascript object undefined

我正在编写一个处理变量的脚本,gameRegion如下所示:

//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;
};
Run Code Online (Sandbox Code Playgroud)

我收到控制台错误:TypeError: 'undefined' is not an object (evaluating 'gameRegion.yPos').据推测,这意味着我没有正确定义gameRegion或变量yPos.我一直在看这段代码一段时间,我似乎无法找到问题所在.

希望你会看到我没有的东西,但如果我没有包含必要的上下文代码,请告诉我.在此先感谢您的帮助.

Aks*_*Aks 7

你必须处理'undefined'.可以通过以下方式完成:

typeof(foo) == 'undefined'
typeof foo !== 'undefined'
window.foo !== undefined
'foo' in window
Run Code Online (Sandbox Code Playgroud)

前三个应该是等价的(只要foo不被局部变量遮蔽),而最后一个将在定义全局变量但未初始化(或显式设置为未定义)时返回true.