Last active
August 29, 2015 14:01
-
-
Save kwo/6b41882abd2e12ad9c3d to your computer and use it in GitHub Desktop.
NodeJS properties test
This file contains 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
#! /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