Skip to content

Instantly share code, notes, and snippets.

@lmammino
Last active July 19, 2017 20:02
Show Gist options
  • Select an option

  • Save lmammino/cf184f9c749490dfb42d5dec0cd6f074 to your computer and use it in GitHub Desktop.

Select an option

Save lmammino/cf184f9c749490dfb42d5dec0cd6f074 to your computer and use it in GitHub Desktop.
Javascript getters/setters quick demo - expanded from Node.js Design Patterns (Second Edition) - https://www.nodejsdesignpatterns.com/
const person = {
name: 'George',
surname: 'Boole',
get fullname () {
console.log('** getting fullname')
return this.name + ' ' + this.surname
},
set fullname (fullname) {
console.log('** setting fullname to', fullname)
let parts = fullname.split(' ')
this.name = parts[0]
this.surname = parts[1]
}
}
console.log(person.fullname) // (** getting fullname) "George Boole"
console.log(person.fullname = 'Alan Turing') // (** setting fullname to Alan Turing') "Alan Turing"
console.log(person.name) // “Alan"
console.log(person.fullname) // (** getting fullname) "Alan Turing"
// inspecting the object
console.log(person) // { name: 'Alan', surname: 'Turing', fullname: [Getter/Setter] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment