Skip to content

Instantly share code, notes, and snippets.

@potikanond
Last active January 21, 2020 00:46
Show Gist options
  • Save potikanond/ae86ee5a6bfd31d799b713b91bfe5e47 to your computer and use it in GitHub Desktop.
Save potikanond/ae86ee5a6bfd31d799b713b91bfe5e47 to your computer and use it in GitHub Desktop.
JavaScript OOP ES5 and ES6
// 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());
// 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