javascript - undefined variable 何时抛出 Uncaught TypeError 而不是仅仅具有值 'undefined' ?

标签 javascript error-handling undefined undefined-behavior

基本上,在我正在编辑的代码中,有一个函数接收一个对象参数,该参数有 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 正是这样的:变量,名称,您在代码中使用过,但运行时不知道它应该引用什么,因为您从未引入过 变量名。

这里您清楚地引入了 foobar 作为函数参数。运行时很清楚这些变量来自哪里,它们的作用域是什么等等。很简单,它们还没有被分配一个值/它们持有值未定义 undefined variable 是您突然引用的变量,而没有在任何地方使用 varletconst 或作为函数参数。例如:

console.log(foo);

我从未定义过 foo 是什么,它来自哪里或者它的值应该是什么,所以这是一个错误。

关于javascript - undefined variable 何时抛出 Uncaught TypeError 而不是仅仅具有值 'undefined' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52605422/

相关文章:

javascript - 带 anchor 按钮的多束 Accordion 效果

error-handling - 有什么方法可以快速查看所有现有的SSIS包事件处理程序?

javascript - 从 javascript 函数返回 `undefined` 还是 `null` 更好?

javascript - 开始拖动时可拖动消失

javascript - ReactJS 和自动对焦

javascript - 为什么 JavaScript 中的以下代码不会将当前日期向前移动五天?

c# - 错误: Type or namespace not found

c - 整数范围和溢出

javascript - 计算器:变量在 "if else"语句中以某种方式未定义

c++ - 使用 -O0 时 g++ 在 undefined reference 处停止