Last active
January 21, 2020 00:46
-
-
Save potikanond/ae86ee5a6bfd31d799b713b91bfe5e47 to your computer and use it in GitHub Desktop.
JavaScript OOP ES5 and ES6
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
// OOP <ES5-2016> - constructive function | |
function Person(firstName, lastName, dob) { | |
// properties | |
this.fname = firstName; | |
this.lname = lastName; | |
// this.dob = dob; | |
this.dob = (dob === undefined)? new Date(): new Date(dob); | |
// methods - listed as properties in the object (NOT in prototype) | |
/* this.getBirthYear = function () { return this.dob.getFullYear(); } | |
this.getFullName = function() { return `${this.fname} ${this.lname}`; } */ | |
} | |
// add prototype function | |
Person.prototype.getBirthYear = function() { | |
return this.dob.getFullYear(); | |
} | |
Person.prototype.getFullName = function() { | |
return `${this.fname} ${this.lname}`; | |
} | |
// Instantiate object with constructor | |
const p1 = new Person('John','Doe','5-Dec-1990'); | |
console.log(p1); | |
const p2 = new Person(); | |
console.log(p2); | |
console.log(p1.dob.getFullYear()); | |
console.log(p2.getBirthYear()); | |
console.log(p1.getFullName()); |
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
// OOP <ES6-2017> - recommended | |
class PersonC { | |
constructor(firstName, lastName, dob) { | |
// properties | |
this.fname = firstName; | |
this.lname = lastName; | |
// this.dob = dob; | |
this.dob = (dob === undefined)? new Date(): new Date(dob); | |
} | |
getBirthYear = function() { | |
return this.dob.getFullYear(); | |
} | |
getFullName = function() { | |
return `${this.fname} ${this.lname}`; | |
} | |
// getBirthYear = () => this.dob.getFullYear(); | |
// getFullName = () => `${this.fname} ${this.lname}`; | |
} | |
const p3 = new PersonC('Jane','Doe','15-Aug-2006'); | |
console.log(p3); | |
console.log(p3.getBirthYear()); | |
console.log(p3.getFullName()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment