CoffeeScript Existential操作符和这 [英] CoffeeScript Existential Operator and this
问题描述
我注意到一些有点奇怪的CoffeeScript编译器,并想知道这是否正确的行为或不。如果是正确的,我很好奇为什么会有差别。
鉴于以下CoffeeScript:
如果@myVar?
alert myVar
我期望它可以像这样编译成JavaScript:
if(typeof this.myVar!==undefined&& this.myVar!== null){
alert (myVar);
}
但是CoffeeScript编译器输出的是:
if(this.myVar!= null){
alert(myVar);
}
如果我不引用此(或任何其他父对象) CoffeeScript按我的预期编译。
这是正确的行为吗?
编辑:
若要进一步说明。这不会发生只有这一点,但对象的任何其他属性。例如,如果我用下面的代码替换上面的CoffeeScript,它仍然只会编译!= null...
if myVar.myProp?
alert myVar
myVar = 10
如果myVar?
alert myVar
Coffeescript编译器能够看到 myVar
真的在第一行定义,所以可以省略 typeof myVar!==undefined
检查。
if(myVar!== null){
alert(myVar);
}
但在这种情况下:
如果myVar?
alert myVar
编译器不能保证 myVar
实际上是定义的,所以需要额外的检查:
if(typeof myVar!==undefined& ;& myVar!== null){
alert(myVar);
}
因此,答案是:Coffeescript编译器试图聪明地生成高效的代码
EDIT
Coffeescript处理属性的方式也是正确的: this.prop $如果没有定义属性,c $ c>将返回
undefined
。 !=
将它转换为null。这就是为什么我们不需要额外的检查。
简单来说:
- 访问未定义的变量throws exception - - 需要检查
typeof
- 访问undefined属性返回
undefined
- just!=
够了
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..
Given the following CoffeeScript:
if @myVar?
alert myVar
I was expecting it to compile to JavaScript like this:
if (typeof this.myVar !== "undefined" && this.myVar !== null) {
alert(myVar);
}
But instead what the CoffeeScript compiler outputs is this:
if (this.myVar != null) {
alert(myVar);
}
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?
Edit:
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
In the case of:
myVar = 10
if myVar?
alert myVar
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);
}
But in this case:
if myVar?
alert myVar
compiler can't guarantee that myVar
is actually defined, so extra check is required:
if (typeof myVar !== "undefined" && myVar !== null) {
alert(myVar);
}
So, the answer is: Coffeescript compiler tries to be smart to produce efficient code.
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:
- accessing undefined variable throws exception -- need to check
typeof
- accessing undefined property returns
undefined
-- just!=
is enough
这篇关于CoffeeScript Existential操作符和这的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!