将CoffeeScript问号语法翻译成Javascript

时间:2021-07-15 01:01:11

I have a CoffeeScript snippet that uses the Question mark operator. I need to translate into Javascript syntax. The snippet is like the following.

我有一个使用问号运算符的CoffeeScript代码段。我需要翻译成Javascript语法。该片段如下所示。

closeItem: (item) ->
    item.close() if item?.close and not item.isClosed

I tried to run into CoffeeScript site and the result is the following.

我试图遇到CoffeeScript网站,结果如下。

({
  closeItem: function(item) {
    if ((item != null ? item.close : void 0) && !item.isClosed) {
      return item.close();
    }
  }
});

Is this correct? Based on my knowledge (I'm new both on Javascript and CoffeeScript) I would translate as

它是否正确?根据我的知识(我是Javascript和CoffeeScript的新手)我会翻译为

closeItem: function(item) {
    if(item && item.close && !item.isClosed) item.close();
}

Am I missing something?

我错过了什么吗?

1 个解决方案

#1


4  

Your translation is good, although you might want to return the return value of item.close() (as that's what the CoffeeScript version does). CoffeeScript's translation is probably more general-purpose (for instance, it would handle a?.foo if a were the number 0). If you know item is an object, your version is fine.

你的翻译很好,虽然你可能想要返回item.close()的返回值(就像CoffeeScript版本那样)。 CoffeeScript的翻译可能更通用(例如,如果数字为0,它将处理?.foo)。如果您知道item是一个对象,那么您的版本就可以了。

#1


4  

Your translation is good, although you might want to return the return value of item.close() (as that's what the CoffeeScript version does). CoffeeScript's translation is probably more general-purpose (for instance, it would handle a?.foo if a were the number 0). If you know item is an object, your version is fine.

你的翻译很好,虽然你可能想要返回item.close()的返回值(就像CoffeeScript版本那样)。 CoffeeScript的翻译可能更通用(例如,如果数字为0,它将处理?.foo)。如果您知道item是一个对象,那么您的版本就可以了。