基本上,在我正在编辑的代码中,有一个函数接收一个对象参数,该参数有 2 个可能的键/值对,但根据某些条件仅使用其中一个:
这是将 foobar
解构为各个键的函数:
function someFunction({ foo, bar }) {
console.log(foo); // can be either { foo: "123"} or undefined
console.log(bar); // can be either { bar: "321"} or undefined
}
这是我们将 foobar
参数传递给 someFunction()
的地方:
function anotherFunction(foobar) {
console.log(foobar); // can be either { foo: "123"} or { bar: "321"}
someFunction(foobar);
}
这是 foobar
参数的来源,其值取决于某些条件:
if(someConditionIsMet) {
anotherFunction({ foo: "123"});
} else {
anotherFunction({ bar: "321"});
}
但有时,如果我在某个地方有一个 undefined variable ,我会得到一个Uncaught TypeError: Cannot read property of undefined
并且程序根本不会运行。
例如当我调用 someFunction(foobar)
时,我期望得到一个未捕获的类型错误,因为其中一个变量肯定是未定义
。但是,这里该函数仍然运行。
为什么会这样?
最佳答案
undefined variable 正是这样的:变量,名称,您在代码中使用过,但运行时不知道它应该引用什么,因为您从未引入过 变量名。
这里您清楚地引入了 foo
和 bar
作为函数参数。运行时很清楚这些变量来自哪里,它们的作用域是什么等等。很简单,它们还没有被分配一个值/它们持有值未定义
。 undefined variable 是您突然引用的变量,而没有在任何地方使用 var
、let
、const
或作为函数参数。例如:
console.log(foo);
我从未定义过 foo
是什么,它来自哪里或者它的值应该是什么,所以这是一个错误。
关于javascript - undefined variable 何时抛出 Uncaught TypeError 而不是仅仅具有值 'undefined' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52605422/