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

时间:2012-05-16 05:51:37

标签: coffeescript

The following CoffeeScript code

foo = (x) ->
  alert("hello") unless x?
  alert("world") unless y?

编译为:

var foo;

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

为什么foo的参数x未针对undefined进行检查,而y是?

1 个答案:

答案 0 :(得分:9)

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

>a == 1
ReferenceError: a is not defined

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

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

// y has never been declared or assigned to
>typeof(y) == "undefined"
true
相关问题