为什么在使用"x?"时不检查函数参数"x"是否为"未定义"?

Mis*_*hko 6 coffeescript

以下CoffeeScript代码:

foo = (x) ->
  alert("hello") unless x?
  alert("world") unless y?
Run Code Online (Sandbox Code Playgroud)

编译为:

var foo;

foo = function(x) {
  if (x == null) {
    alert("hello");
  }
  if (typeof y === "undefined" || y === null) {
    return alert("world");
  }
};
Run Code Online (Sandbox Code Playgroud)

为什么foo"的说法x是不检查undefined,而y为?

use*_*515 9

未定义的检查是为了防止在检索不存在的标识符的值时引发的ReferenceError异常:

>a == 1
ReferenceError: a is not defined
Run Code Online (Sandbox Code Playgroud)

编译器可以看到x标识符存在,因为它是函数参数.

编译器无法判断y标识符是否存在,因此需要检查y是否存在.

// y has never been declared or assigned to
>typeof(y) == "undefined"
true
Run Code Online (Sandbox Code Playgroud)

  • 未定义的不同含义.如果调用foo()或foo(undefined),则x === [undefined](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined).标识符x存在(它只是设置为特定值),因此您不会获得ReferenceError.比较仍然有效,因为undefined == null(注意它使用两个等号,而不是三个). (2认同)