Skip to content

Instantly share code, notes, and snippets.

@whal-e3
Last active November 7, 2020 00:53
Show Gist options
  • Save whal-e3/2c1bda07e9a3b9a3006a2b7ab4f280ce to your computer and use it in GitHub Desktop.
Save whal-e3/2c1bda07e9a3b9a3006a2b7ab4f280ce to your computer and use it in GitHub Desktop.
JS constructor without class and with class - prototype
// Object prototype
// |
// Person prototype
// |
// Person instance ex) john
// Constructor
function Person(firstName, lastName, dob) {
this.firstName = firstName;
this.lastName = lastName;
this.birthday = new Date(dob);
// this.calculateAge = function () {
// const diff = Date.now() - this.birthday.getTime();
// const ageDate = new Date(diff);
// return Math.abs(ageDate.getUTCFullYear() - 1970);
// };
}
// Calculate age
Person.prototype.calculateAge = function () {
const diff = Date.now() - this.birthday.getTime();
const ageDate = new Date(diff);
return Math.abs(ageDate.getUTCFullYear() - 1970);
};
const john = new Person('John', 'Doe', '8-12-90');
const mary = new Person('Mary', 'Johnson', 'March 20 1978');
console.log(mary);
// with class -------------------------------------------------------------------------
class Person {
constructor(firstName, lastName, dob) {
this.firstName = firstName;
this.lastName = lastName;
this.birthday = new Date(dob);
}
calculateAge() {
const diff = Date.now() - this.birthday.getTime();
const ageDate = new Date(diff);
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
}
const john = new Person('John', 'Doe', '8-12-90');
const mary = new Person('Mary', 'Johnson', 'March 20 1978');
console.log(mary);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment