Dev Blog

JavaScript allows You to define getter and setter for property. So that this property can compute value and return it. This can be used to sanitize value or to return value based

on other object values. This can be done with Object.defineProperty function. It takes object as a first argument, property name as a second argument - defined as string. The third argument is object defining get and set methods, as well as indicating whether property should be enumerable. Enumerable property will be for example included in loops.

When defining in class constructor, ensure that the parent constructor will be called using super keyword.

Example of getter and setter

  class User extends Model  

firstName: '' lastName: '' fullName: ''
constructor: (data) ->
Object.defineProperty @, 'fullName', {
get: () =>
return "#{@firstName} #{@lastName}"
enumerable: true,
set: (value) -> # Ignore
}


super(data)

In the example above, accessing fullName property will concatenate firstName and lastName.

Usage of example User class

user = new User
user.firstName = 'John'
user.lastName = 'Smith'
console.log user.fullName

This will output John Smith to browsers console.