Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's another approach for defining properties with getters and setters in CoffeeScript that maintains a relatively clean syntax without adding anything to the global Function prototype (which I'd rather not do):</p> <pre><code>class Person constructor: (@firstName, @lastName) -&gt; Object.defineProperties @prototype, fullName: get: -&gt; "#{@firstName} #{@lastName}" set: (name) -&gt; [@firstName, @lastName] = name.split ' ' p = new Person 'Robert', 'Paulson' console.log p.fullName # Robert Paulson p.fullName = 'Space Monkey' console.log p.lastName # Monkey </code></pre> <p>It works well with many properties. For example, here's a Rectangle class that is defined in terms of (x, y, width, height), but provides accessors for an alternative representation (x1, y1, x2, y2):</p> <pre><code>class Rectangle constructor: (@x, @y, @w, @h) -&gt; Object.defineProperties @prototype, x1: get: -&gt; @x set: (@x) -&gt; x2: get: -&gt; @x + @w set: (x2) -&gt; @w = x2 - @x y1: get: -&gt; @y set: (@y) -&gt; y2: get: -&gt; @y + @h set: (y2) -&gt; @w = y2 - @y r = new Rectangle 5, 6, 10, 11 console.log r.x2 # 15 </code></pre> <p>Here's <a href="http://coffeescript.org/#try:class%20Rectangle%0A%20%20constructor%3A%20(%40x%2C%20%40y%2C%20%40w%2C%20%40h)%20-%3E%0A%20%20Object.defineProperties%20%40prototype%2C%0A%20%20%20%20x1%3A%0A%20%20%20%20%20%20get%3A%20-%3E%20%40x%0A%20%20%20%20%20%20set%3A%20(%40x)%20-%3E%0A%20%20%20%20x2%3A%0A%20%20%20%20%20%20get%3A%20-%3E%20%40x%20%2B%20%40w%0A%20%20%20%20%20%20set%3A%20(x2)%20-%3E%20%40w%20%3D%20x2%20-%20%40x%0A%20%20%20%20y1%3A%0A%20%20%20%20%20%20get%3A%20-%3E%20%40y%0A%20%20%20%20%20%20set%3A%20(%40y)%20-%3E%0A%20%20%20%20y2%3A%0A%20%20%20%20%20%20get%3A%20-%3E%20%40y%20%2B%20%40h%0A%20%20%20%20%20%20set%3A%20(y2)%20-%3E%20%40w%20%3D%20y2%20-%20%40y%0A%0Ar%20%3D%20new%20Rectangle%205%2C%206%2C%2010%2C%2011%0Aconsole.log%20r.x2%20%23%2015" rel="noreferrer">the corresponding JavaScript code</a>. Enjoy!</p>
    singulars
    1. This table or related slice is empty.
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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