Last active
November 25, 2019 09:02
-
-
Save harbirchahal/301569d7bd7b9a78c8bd2d682f2462df to your computer and use it in GitHub Desktop.
Constructor OO pattern in JavaScript
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
/** Person pseudo class. */ | |
const Person = (function () { | |
function Person(firstName, lastName) { | |
this.firstName = firstName; | |
this.lastName = lastName; | |
} | |
Person.prototype.alias = function () { | |
return this.firstName.charAt(0) + this.lastName.charAt(0); | |
} | |
Person.prototype.fullName = function () { | |
return this.firstName + ' ' + this.lastName; | |
} | |
return Person; | |
})(); | |
const p = new Person('Lorem', 'Ipsum'); | |
console.log(p.fullName()); // Lorem Ipsum | |
/** Professional pseudo class. */ | |
const Professional = (function () { | |
function Professional(honorific, firstName, lastName) { | |
Person.call(this, firstName, lastName); | |
this.honorific = honorific; | |
} | |
/** Prototype chain. */ | |
Professional.prototype = Object.create(Person.prototype); | |
Professional.prototype.professionalName = function () { | |
return this.honorific + ' ' + this.firstName + ' ' + this.lastName; | |
} | |
return Professional; | |
})(); | |
const prof = new Professional('Mr.', 'Lorem', 'Ipsum'); | |
console.log(prof.fullName()); // Lorem Ipsum | |
console.log(prof.professionalName()); // Mr. Lorem Ipsum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment