Created
June 9, 2015 15:56
-
-
Save andy-polhill/6731301b62f979899285 to your computer and use it in GitHub Desktop.
Experiments with ES6 class syntax and private members (through Babel0
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
class Person { | |
constructor(options) { | |
this.firstname = options.firstname; | |
this.lastname = options.lastname; | |
Person.privateData.set(this, { dob: options.dob }); | |
} | |
get fullname() { | |
return this.firstname + ' ' + this.lastname; | |
} | |
greet() { | |
console.log('Hello my name is ' + this.fullname); | |
} | |
sayAge() { | |
console.log('I am ' + Person.calculateAge(Person.privateData.get(this).dob) + ' years old'); | |
} | |
static calculateAge(dob) { | |
var ageDate = new Date(Date.now() - dob.getTime()); // miliseconds from epoch | |
return Math.abs(ageDate.getUTCFullYear() - 1970); | |
} | |
static privateData = new WeakMap(); | |
} | |
class Customer extends Person { | |
constructor(options) { | |
super(options); | |
} | |
} | |
var andy = new Person({ | |
'firstname': 'Andy', | |
'lastname': 'Polhill', | |
'dob': new Date('12/13/1979') | |
}); | |
var charles = new Person({ | |
'firstname': 'Charles', | |
'lastname': 'Dickens', | |
'dob': new Date('2/7/1812') | |
}); | |
andy.greet(); | |
andy.sayAge(); | |
charles.greet(); | |
charles.sayAge(); | |
andy.dob = new Date('12/13/1986'); | |
console.log(andy.dob) | |
andy.sayAge(); | |
var sam = new Customer({ | |
'firstname': 'Sam', | |
'lastname': 'Gray', | |
'dob': new Date('05/10/1999') | |
}); | |
sam.greet(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment