Skip to content

Instantly share code, notes, and snippets.

@kwo
Last active August 29, 2015 14:01
Show Gist options
  • Save kwo/6b41882abd2e12ad9c3d to your computer and use it in GitHub Desktop.
Save kwo/6b41882abd2e12ad9c3d to your computer and use it in GitHub Desktop.
NodeJS properties test
#! /usr/bin/env node
// Method 1, using get and set literals instead of the function keyword
var time1 = {
seconds: 0,
get milliseconds() {return this.seconds * 1000;},
set milliseconds(x) {this.seconds = x / 1000;}
};
time1.milliseconds = 1750;
console.log(time1.seconds, time1.milliseconds); // outputs 1.75 1750;
// Method 2, using defineProperty
var time2 = {
seconds: 0
};
Object.defineProperty(time2, 'milliseconds', {
get: function getMilliseconds() {return this.seconds * 1000;},
set: function setMilliseconds(x) {this.seconds = x / 1000;}
});
time2.milliseconds = 1750;
console.log(time2.seconds, time2.milliseconds); // outputs 1.75 1750;
// Method 3, using the deprecated __defineGetter__, __defineSetter__ methods
var time3 = {};
time3.seconds = 0;
time3.__defineGetter__('milliseconds', function() { return this.seconds * 1000;} );
time3.__defineSetter__('milliseconds', function(x) { this.seconds = x / 1000;});
time3.milliseconds = 1750;
console.log(time3.seconds, time3.milliseconds); // outputs 1.75 1750;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment