简体   繁体   中英

Coffeescript Syntax: Structure is wrong

I simplified my code to show the problem. When I use this Coffeescript snippet:

$("<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.

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.

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.

Parentheses in CoffeeScript are optional, but that doesn't mean you're not supposed to use them. 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 ;)

coco and livescript (on npm or github) both are derived from coffeescript and are more "space sensitive", which allows you to do:

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

and

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

which both compile to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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