To create properties of an object we create a construction function and then use the keyword this to assign those properties. To add a method to an object we again use the this keyword, but we assign it to a function:
// A constructor functionfunction Person(firstName, lastName, dob) { this.firstName = firstName; this.lastName = lastName; this.dob = new Date(dob); // Using a constructor to create a date class // Adding methods this.getBirthYear = function() { return this.dob.getFullYear() // Using the Date method } this.getFullName = function() { return `${this.firstName} ${this.lastName}` }}
To create an instance of this object we must use the new keyword:
const person1 = new Person("John", "Smith", "4-3-1980")
Object prototypes
When creating an object and adding methods as above, any use of console.log on the object will include the methods we wrote, since they are nothing more than other attributes of that object itself.
For readability and better access control, we can add the functionality we require to the __proto__ (or prototype of the constructor “class”) constructor that each function has:
// Assuming the existence of a function Person object...Person.prototype.getBirthYear = function () { return this.dob.getFullYear();}