Skip to content

Instantly share code, notes, and snippets.

@jackfranklin
Last active December 31, 2015 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackfranklin/8029454 to your computer and use it in GitHub Desktop.
Save jackfranklin/8029454 to your computer and use it in GitHub Desktop.
ES5 Getters and Setters
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);
@jackfranklin
Copy link
Author

Of course, in this instance firstName and lastName don't have to be defined this way, but I thought it was sensible to purely to see the use case for enumerable?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment