Coffeescript 为什么函数参数是;x";未检查是否有“错误”;“未定义”;当使用;x;?
: 汇编为:Coffeescript 为什么函数参数是;x";未检查是否有“错误”;“未定义”;当使用;x;?,coffeescript,Coffeescript,: 汇编为: var foo; foo = function(x) { if (x == null) { alert("hello"); } if (typeof y === "undefined" || y === null) { return alert("world"); } }; 为什么foo的参数x没有检查未定义的,而y没有检查?未定义的检查是为了防止检索不存在的标识符的值时引发引用错误异常: >a == 1 ReferenceError: a
var foo;
foo = function(x) {
if (x == null) {
alert("hello");
}
if (typeof y === "undefined" || y === null) {
return alert("world");
}
};
为什么
foo
的参数x
没有检查未定义的,而y
没有检查?未定义的检查是为了防止检索不存在的标识符的值时引发引用错误异常:
>a == 1
ReferenceError: a is not defined
编译器可以看到x标识符存在,因为它是函数参数
编译器无法判断y标识符是否存在,因此需要检查y是否存在
// y has never been declared or assigned to
>typeof(y) == "undefined"
true
但是,如果调用foo
时没有参数,例如bar=foo()
,那么x
不是undefined
?undefined的不同含义。如果调用foo()或foo(未定义),则x==。标识符x存在(它只是被设置为一个特定的值),因此不会出现ReferenceError。比较仍然有效,因为undefined==null(注意它使用的是两个等号,而不是三个等号)。x==null
如果x
是一个完全未知的变量,则会失败,而typeof x
在这种情况下会返回“undefined”
,即使x
没有值未定义
,它也不存在。
// y has never been declared or assigned to
>typeof(y) == "undefined"
true