简体   繁体   English

Coffeescript语法:结构错误

[英]Coffeescript Syntax: Structure is wrong

I simplified my code to show the problem. 我简化了代码以显示问题。 When I use this Coffeescript snippet: 当我使用此Coffeescript代码段时:

$("<div>")
.text "hi"
.appendTo "body"

I expect it to compile like this: 我希望它可以这样编译:

$("<div>").text("hi").appendTo("body")

What it does instead is: 相反,它的作用是:

$("<div>").text("hi".appendTo("body"))

I found out that you can keep the brackets and it works, but I guess it's not the way you're supposed to write Coffeescript. 我发现您可以保留方括号并且可以使用,但是我想这不是您应该编写Coffeescript的方式。

Can anyone tell me how I'm supposed to write it so it compiles to the desired output? 谁能告诉我应该怎么写才能编译成所需的输出? Thank you very much. 非常感谢你。

Add the parentheses. 添加括号。

As far a good style goes, you should only omit syntax when it clutters your intent. 就好的样式而言,仅应在语法混乱时才应省略语法。 In this case, omitting them loses your intent. 在这种情况下,忽略它们会失去您的意图。 Form follows function. 形式服从功能。 You need the parentheses here inorder to declare precedent, and Coffeescript has support for them for that reason. 为了声明先例,您需要在此处加上括号,Coffeescript为此提供了支持。

I found out that you can keep the brackets and it works, but I guess it's not the way you're supposed to write Coffeescript. 我发现您可以保留方括号并且可以使用,但是我想这不是您应该编写Coffeescript的方式。

Parentheses in CoffeeScript are optional, but that doesn't mean you're not supposed to use them. CoffeeScript中的括号是可选的,但这并不意味着您不应该使用它们。 Feel free to use them! 随时使用它们! In some cases, like yours, they're even required. 在某些情况下,例如您的情况,甚至是必需的。

To me, the big win with optional parentheses is for anonymous callbacks and other cases where the parentheses would otherwise span several lines, like this: 对我而言,带可选括号的最大优势是匿名回调和其他情况下括号会跨越几行的情况,例如:

foo 'bar', (err, res) ->
  # Do stuff

Which, to me, is superior to 对我而言,这优于

foo('bar', (err, res) ->
  # Do stuff
)

But even if that's your style, go for it! 但是,即使这是您的风格,也要坚持下去!

So, to summarize, just write: 因此,总结一下,只需编写:

$("<div>")
  .text("hi")
  .appendTo("body")

Edit: Or even 编辑:甚至

$("<div>").text("hi").appendTo("body")

In this particular case, though, you could of course do: 但是,在这种情况下,您当然可以:

$("<div>", text: "hi").appendTo("body")

TIMTOWDY ;) TIMTOWDY;)

coco and livescript (on npm or github) both are derived from coffeescript and are more "space sensitive", which allows you to do: coco和livescript (在npm或github上)都源自coffeescript,并且对空间更敏感,您可以执行以下操作:

$ "<div>" .text "hi" .appendTo "body"

and

$("<div>")
  .text "hi"
  .appendTo "body"

which both compile to 两者都编译成

$("<div>").text("hi").appendTo("body");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM