Note that there are some explanatory texts on larger screens.

plurals
  1. POHaving both object.property and object.property.method() available in coffeescript
    primarykey
    data
    text
    <p>[update] My question may not be clear enough... Further clarification of what I would like to accomplish :</p> <p>I retrieve objects like this one:</p> <pre><code>p = name: first: 'alan' last: 'smith' </code></pre> <p>and want to create a structure (one class, multiple classes ?) to be able to write things like this ultimately:</p> <pre><code>person.name # alan smith person.name.toCap() #Alan Smith person.name.first # alan person.name.first.toCap() # Alan person.name.last # smith person.name.last.toCap() # Smith ... </code></pre> <p>so :</p> <ol> <li>Is there a way to have both person.name and person.name.first ?</li> <li>Is there a better way to extend object properties with methods rather than extending native types like <em>String</em> ?</li> </ol> <hr> <p>[original]</p> <p>Looking for the right way to do this in coffee : </p> <pre><code>console.log person.name.last #smith console.log person.name.last.capitalize() # SMITH console.log person.name.last.initial() # S </code></pre> <p>I have come up with the following solution, but would like to make sure this is the way to go...</p> <pre><code>String::toCap = (remainingToLower=false) -&gt; @[0].toUpperCase() + if remainingToLower then @[1..-1].toLowerCase() else @[1..-1] Number::random = (percent) -&gt; offset = @ * percent / 100 parseInt(Math.floor(Math.random() * 2 * offset) + @ - offset) class Name constructor: (@first, @last) -&gt; class Person constructor: (@name, @age) -&gt; toString: () =&gt; "#{@name.first.toCap(true)} #{@name.last.toCap(true)} (#{@age.random(25)})" # GO ---------------------------&gt; p = new Person(new Name, 18) p.name.first = 'alaN' p.name.last = 'smith' console.log "#{p.toString()}" </code></pre> <p>Thanks for your feedback.</p> <p><a href="http://plnkr.co/edit/ovwj7z" rel="nofollow" title="Plunk Here">Plunk Here</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload