Last active
November 7, 2020 00:53
-
-
Save whal-e3/2c1bda07e9a3b9a3006a2b7ab4f280ce to your computer and use it in GitHub Desktop.
JS constructor without class and with class - prototype
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
// 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