CoffeeScript 存在运算符和 this [英] CoffeeScript Existential Operator and this
问题描述
我注意到 CoffeeScript 编译器有些奇怪,想知道这是否是正确的行为.如果它是正确的,我很好奇为什么会有区别..
I noticed something a little odd with the CoffeeScript compilier and was wondering if this was correct behavior or not. If it is correct I'm curious why there is a difference..
鉴于以下 CoffeeScript:
Given the following CoffeeScript:
if @myVar?
alert myVar
我期待它像这样编译成 JavaScript:
I was expecting it to compile to JavaScript like this:
if (typeof this.myVar !== "undefined" && this.myVar !== null) {
alert(myVar);
}
但是 CoffeeScript 编译器的输出是这样的:
But instead what the CoffeeScript compiler outputs is this:
if (this.myVar != null) {
alert(myVar);
}
如果我不引用这个(或任何其他父对象),CoffeeScript 将按照我的预期编译.
If I don't reference this (or any other parent object), the CoffeeScript compiles as I would expect.
这是正确的行为吗?如果是这样,为什么它在使用时会有所不同?
Is this the correct behavior? If so, why does it work different when using this?
补充一点说明.这不仅仅发生在这个,而是对象的任何其他属性.例如,如果我将上面的 CoffeeScript 替换为下面的内容,它仍然只能使用!= null"进行编译...
To add a little more clarification. This doesn't happen with only this, but any other properties of objects. For instance, if I were replace the above CoffeeScript with what's below it still would compile with only "!= null"...
if myVar.myProp?
alert myVar
推荐答案
情况:
myVar = 10
if myVar?
alert myVar
Coffeescript 编译器能够看到 myVar
确实定义在第一行,所以它可以省略 typeof myVar !== "undefined"
检查.
Coffeescript compiler is able to see that myVar
is really defined in the first line, so it can omit typeof myVar !== "undefined"
check.
if (myVar !== null) {
alert(myVar);
}
但在这种情况下:
if myVar?
alert myVar
编译器不能保证 myVar
确实被定义了,所以需要额外检查:
compiler can't guarantee that myVar
is actually defined, so extra check is required:
if (typeof myVar !== "undefined" && myVar !== null) {
alert(myVar);
}
所以,答案是:Coffeescript 编译器试图聪明地产生高效的代码.
So, the answer is: Coffeescript compiler tries to be smart to produce efficient code.
编辑Coffeescript 处理属性的方式也是正确的:如果属性未定义,this.prop
将返回 undefined
.!=
会将其转换为 null.这就是我们不需要额外检查的原因.
简而言之:
EDIT
The way Coffeescript deals with properties is also correct: this.prop
will return undefined
if property is not defined. !=
will convert it to null. That is why we don't need additional check.
In few words:
- 访问未定义的变量抛出异常——需要检查
typeof
- 访问未定义的属性返回
undefined
--!=
就足够了
- accessing undefined variable throws exception -- need to check
typeof
- accessing undefined property returns
undefined
-- just!=
is enough
这篇关于CoffeeScript 存在运算符和 this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!