Last active
July 19, 2017 20:02
-
-
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/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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