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为?
未定义的检查是为了防止在检索不存在的标识符的值时引发的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)
| 归档时间: |
|
| 查看次数: |
138 次 |
| 最近记录: |