为什么下划线的_.isUndefined(变量)会给出一个错误,即未定义变量?

Jam*_*ami 9 javascript undefined underscore.js

在Chrome中,我从这行代码中得到"Uncaught ReferenceError:targetNode is not defined" console.log(_.isUndefined(targetNode));.

我得到了同样的错误,当我做console.log(targetNode === void(0));console.log(targetNode);.

typeof targetNode === "undefined" 按预期返回true,但我的理解是void(0)比较更有效.

我可以通过设置默认值来解决这个问题,targetNode或者我可以使用typeof targetNode === "undefined",但我试图理解为什么变量未定义的测试会在变量未定义时阻塞.

Nie*_*sol 10

当你要求时targetNode,它会查找一个局部变量,然后在后续的父作用域中查找,直到它到达链的末尾.如果它仍然没有找到它,则会出现错误.

typeof它的特殊之处在于它类似于try..catch获取变量,并"undefined"在catch中返回.非本机代码(例如isUndefined)不能这样做,因为必须解析变量才能将其传递给函数.

但是,如果定义了符号,则可以有效地传递它.例如:

function test(param) {
    console.log(_.isUndefined(param));
}
test("argument");
test(); // undefined argument
Run Code Online (Sandbox Code Playgroud)

或者另一个例子:

function test() {
    console.log(_.isUndefined(foo)); // true, no error due to hoisting
    var foo = 3;
    console.log(_.isUndefined(foo)); // false, foo is defined now.
}
Run Code Online (Sandbox Code Playgroud)

您还可以指定显式来源,例如window.targetNode.window已定义,因此脚本知道在哪里查找,但是targetNode可能无法定义属性,在这种情况下,您可以获得undefined.