Last active
December 31, 2015 18:49
-
-
Save jackfranklin/8029454 to your computer and use it in GitHub Desktop.
ES5 Getters and Setters
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
var person = {}; | |
Object.defineProperty(person, 'firstName', { | |
get: function() { return firstName; }, | |
set: function(newName) { firstName = newName; }, | |
enumerable: true | |
}); | |
Object.defineProperty(person, 'lastName', { | |
get: function() { return lastName; }, | |
set: function(newName) { lastName = newName; }, | |
enumerable: true | |
}); | |
Object.defineProperty(person, 'fullName', { | |
get: function() { return firstName + " " + lastName }, | |
set: function(fullName) { | |
firstName = fullName.split(" ")[0]; | |
lastName = fullName.split(" ")[1]; | |
} | |
}); | |
person.fullName = "Jack Franklin"; | |
console.log(person.firstName); | |
console.log(person.lastName); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Of course, in this instance
firstName
andlastName
don't have to be defined this way, but I thought it was sensible to purely to see the use case forenumerable
?