admin管理员组

文章数量:1434943

checkbox: (propertyName, {hash}) ->
  ...
  ...

What does this mean?

I'm familiar with the concept of

class Person
  constructor: (name) ->
    @name = name

having a shorthand of

class Person
  constructor: (@name) ->

Does {parameterName} have similar magic?

checkbox: (propertyName, {hash}) ->
  ...
  ...

What does this mean?

I'm familiar with the concept of

class Person
  constructor: (name) ->
    @name = name

having a shorthand of

class Person
  constructor: (@name) ->

Does {parameterName} have similar magic?

Share Improve this question asked Aug 8, 2013 at 17:19 Foolish ChapFoolish Chap 7651 gold badge5 silver badges19 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 6

It's undocumented parameter destructuring

(propertyName, {hash}) ->

Is short for -->

(propertyName, obj) ->
    hash = obj.hash

And this

(propertyName, {hash, something}) ->

Is short for -->

(propertyName, obj) ->
    hash = obj.hash
    something = obj.something

And so on. It works pretty much like the normal destructuring.

This

checkbox = (propertyName, {hash}) ->

piles directly to this in JS

var checkbox;

checkbox = function(propertyName, _arg) {
  var hash;
  hash = _arg.hash;
};

So it gets the property of an object being passed in and sets it as the top level variable name. Whether this is a good thing or not is up for debate, especially since it doesn't seem to be a documented language feature (that I can find)

Coffeescript's site has a helpful tool for investigating things like this: Try Coffeescript

When in doubt, I remend js2coffee to check out the rendered output. You can also use codepen to play around and find the results of certain actions. For example see this as a DEMO

foo = (bar, {baz}) ->
  console.log bar+baz

opts = 
  qaz : 'hey'
  baz : 'wowzers'

foo "go go", opts

# console will log "go go wowzers"

renders to ->

var foo, opts;

foo = function(bar, _arg) {
  var baz;
  baz = _arg.baz;
  return console.log(bar + baz);
};

opts = {
  qaz: 'hey',
  baz: 'wowzers'
};

foo("go go", opts);

It makes it so you can directly use the options names instead of having to do options.property, ie

func = (someValue, {shouldDoSomething, doWork}) ->
   # use option names directly
   doWork someValue if shouldDoSomething

instead of

func = (someValue, options) ->
   options.doWork someValue if options.shouldDoSomething

本文标签: javascriptCoffeescript what does it mean to have curly brackets around a method parameterStack Overflow