开发者

How to return object explicitly in CoffeeScript

开发者 https://www.devze.com 2023-02-09 06:01 出处:网络
This works: myfunc = () -> id: 3 name: \'myname\' 开发者_运维百科 But I want to be explicit about returning object.

This works:

myfunc = () ->
    id: 3
    name: 'myname'
开发者_运维百科

But I want to be explicit about returning object.

myfunc = () ->
    return
        id: 3
        name: 'myname'

But I get "Unexpected 'INDENT'" error. What's wrong with the above code?


myFunc = ->
  return {
    id   : 3
    name : 'myname'
  }

myFunc = ->
  return {} =
    id   : 3
    name : 'myname'

myFunc = ->
  # return
  id   : 3
  name : 'myname'


you should put the return value on the same line or wrap it in () :

myFunc = () ->
  return id:3, name:'myname'

myFunc = () ->
  return (
    id: 3
    name: 'myname'
  )


I think the best way is

myFunc = ->
  return (
    id: 3
    name: 'myname'
  )

because it fits the philosophy of functional programming.


The previous answers are all correct. This works too:

myFunc = () -> 
    {
        id: 3
        name: 'myname'
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消