将未定义的参数传递给函数 - 检查变量是否存在

将未定义的参数传递给函数 - 检查变量是否存在

问题描述:

考虑以下Javascript:

Consider the following Javascript:

function getType(obj){
    return(typeof(obj))
}
alert(typeof(obj))  //alerts "undefined" correctly
alert(getType(obj))   //throws an error: ReferenceError: obj is not defined

为什么会发生这种情况?有没有解决方法?我正在尝试编写一个检查变量是否存在的函数。

Why might this be happening? Is there any workaround? I am trying to write a function which checks if a variable exists.

问题与typeof无关。问题是你不能将未定义的变量传递给函数。

The problem is nothing to do with typeof. The problem is that you cant pass undefined variables to functions.

function doNothing(obj){
}
doNothing(obj);

此代码也会导致错误:未捕获ReferenceError:未定义obj

因此,您在函数内编写的代码无关紧要,因为它不会被调用。错误发生在函数调用之前。

This code too results in the error: Uncaught ReferenceError: obj is not defined
So it doesn't matter what code you write inside your function, as it won't be called. The error happens before the function call.

typeof 是一个运算符,而不是函数。
这就是为什么它的行为方式与函数不同。

typeof is an operator, not a function. This is why it does not behave in the same way as functions.