14

根据咖啡脚本网站

console.log(s) if s?

应该生成

if (typeof s !== "undefined" && s !== null) {
    console.log(s);
}

但是我的浏览器中显示的是

  if (s != null) {
      return console.log(s);
  }

使用 coffee-script-source (1.6.2)、coffee-rails (3.2.2)、rails-backbone (0.7.2)、rails (3.2.13)

这是我的咖啡脚本功能。关于为什么我没有得到咖啡脚本网站所说的我应该得到的任何想法?

window.p = (s) ->
    console.log(s) if s?
4

2 回答 2

31

如果你说只是一个裸露的:

console.log(s) if s?

那么你确实会得到你期望的 JavaScript ( demo ):

if (typeof s !== "undefined" && s !== null) {
  console.log(s);
}

但是,如果s是一个已知变量,例如这里:

f = (s) -> console.log(s) if s?

然后你会得到(演示):

if (s != null) {
  //...
}

s?测试。

那么为什么会有差异呢?在第一种情况下,CoffeeScript 不能保证s任何地方都存在变量,因此它必须进行typeof s检查以避免ReferenceError异常。

但是,如果s已知存在是因为它是函数参数或已被分配为局部变量(因此 CoffeeScript 将生成 a var s),那么您不需要typeof s检查,因为在这种情况下您无法获得 a ReferenceError

这给我们留下了s !== nullvs s != null。下拉到非严格不等式 ( s != null) 允许您检查是否sundefinednull通过单个比较。当您检查时,您使用“是否存在变量”检查来typeof s !== "undefined"包装测试,并且您只需要检查一个严格的测试。undefinedss !== nullnull

于 2013-09-05T02:51:33.067 回答
2

你是对的,

(s) -> console.log(s) if s?

console.log(x) if x?

编译为

(function(s) {
  if (s != null) {
    return console.log(s);
  }
});

if (typeof x !== "undefined" && x !== null) {
  console.log(x);
}

看起来 CoffeeScript 编译器正在为您优化 Javascript,因为在这样的函数参数的情况下,typeof s将永远不会undefineds函数签名中定义的那样,即使它的值为null.

于 2013-09-05T02:47:49.120 回答