我注意到coffeescript编译器的无法解释的行为对我来说:)
例如:
getImage: (req, res) =>
realty_id = req.query.id
if (realty_id?)
结果
ImageController.prototype.getImage = function(req, res) {
var realty_id,
_this = this;
realty_id = req.query.id;
if ((realty_id != null)
但实际上最后一行应该是:if((typeof realty_id!==“undefined”&& realty_id!== null))
当我发表评论“realty_id = req.query.id”时,效果很好。有没有人对此作出解释?
答案 0 :(得分:3)
tldr; typeof x !== "undefined"
。
SO问题CoffeeScript Existential Operator and this包含为什么 CoffeeScript将进行此优化的信息。
现在,要了解为什么在本案例中它是有效的代码生成:
-> x x != null typeof x !== "undefined" && x !== null
---------- --------- -------------------------------------
ANY_TRUE true true
0 true true
null false false
undefined false false
因此,根据逻辑表,它们在语义上是等价的。这是"非严格的" ==
运算符的性质决定了这种比较的结果 - 也许是令人惊讶的结果:关于该主题的SO问题比比皆是。
但是,以下是有时使用typeof x !== "undefined"
的时间/原因的重要区别:不会导致ReferenceError
。如果已知x
是局部变量,那么就没有这样的考虑因素,可以安全地使用较短的(!=
)JavaScript表达式。
如果CoffeeScript中的赋值被注释掉,那么 no 局部变量/绑定的名称为reality_id
- 请注意var
语句也不同 - 并且CoffeeScript会根据需要插入额外的防护。