Skip to content

Instantly share code, notes, and snippets.

@JoeShep
Forked from seanspradlin/properties.js
Created November 5, 2016 19:30
Show Gist options
  • Save JoeShep/74cd4f60bc59cbe7f31e292b1d307123 to your computer and use it in GitHub Desktop.
Save JoeShep/74cd4f60bc59cbe7f31e292b1d307123 to your computer and use it in GitHub Desktop.
Object properties tutorial
function Person(firstName, lastName, age, ssn) {
// Declaring this way by default will make your property
// readable, writable, and enumerable
this.firstName = firstName;
this.lastName = lastName;
// Let's make a getter-only method that returns the
// two values as a whole name
Object.defineProperty(this, 'fullName', {
get: function() {
return this.firstName + ' ' + this.lastName;
},
enumerable: false, // We don't want this to appear in for..in loops
});
// Let's make a getter-setter method to serialize data.
// In this case, we want "age" to always be a number, even
// if the number is a string, and throw an error if it's not
// parseable
var _age = age; // private member scoped to this function
Object.defineProperty(this, 'age', {
set: function(val) {
var v = +val; // convert val to a number
if (Number.isNaN(v)) {
throw new RangeError('age must be a number');
}
_age = v;
},
get: function() {
return _age;
},
enumerable: true, // Display this property in for..in loops
});
// Finally, we'll make a read-only field
Object.defineProperty(this, 'ssn', {
enumerable: true,
readable: true,
writable: false,
value: ssn,
});
}
// Let's create an instance of our new class
var me = new Person('Sean', 'Spradlin', 31, '123-45-6789');
// Now we'll do a for..in loop to check the values
console.log('Displaying keys...');
Object.keys(me).forEach(function(key) {
console.log(key, ':', me[key]);
});
// Let's get the full name
console.log('\nGetting full name...');
console.log(me.fullName);
// Enumerable helps with JSON stringify as well
console.log('\nDisplaying JSON...')
console.log(JSON.stringify(me));
// Setting age as a string will convert it to a number
console.log('\nTesting age...');
me.age = '25'; // string
console.log(typeof me.age, me.age); // number
// Let's try to set it as a non-number string
console.log('\nSetting age as not a number...');
try {
me.age = 'Hello world';
} catch (error) {
console.log('Oops!', error.message);
}
// Now let's try to change our SSN
console.log('\nAttempting to change SSN...');
me.ssn = '555-55-5555';
console.log(me.ssn);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment