Methods are functions in javascript that are related to a specific object. In javascript, you can create an object and attach specific functions to that object (i.e methods of that object). This is best done via the prototype keyword as shown below.
The following creates a Person object constructor with properties of name, birthYear ,company and gender. We then create a method for that object, called `greeting`.
//Create a `Person` object constructor
function Person(name,birthYear,company,gender){
this.name = name;
this.birthYear = birthYear;
this.company = company;
this.gender = gender;
}
// Create a greeting method
Person.prototype.greeting = function (){
return `Hello my name is ${this.name} and I'm the CEO of ${this.company}!`;
}
// Displaying this in the console
const mark = new Person('Mark',1984,'Facebook','male'); // create new person object mark
console.log(mark.greeting()); // call the greeting method.
Create a new prototype called `calculateAge` for the Person object function constructor.
//Create a `Person` object constructor
function Person(name,birthYear,company,gender){
this.name = name;
this.birthYear = birthYear;
this.company = company;
this.gender = gender;
}
// Create a calculateAge method
Person.prototype.calculateAge = function (){
const currentYear = (new Date()).getFullYear(); // get the current year
return currentYear - this.birthYear; // return the age.
}
// display this in the console with the `mark` object.
const mark = new Person('Mark',1984,'Facebook','male'); // create new person object mark
console.log(mark.calculateAge());
All
instances
of the Person object we create (ie. `mark`, `elon`)
have access to the
calculateAge method.
The calculateAge method (or prototype) is just a function that is unique to the
Person
object constructor.
Creating these methods using the prototype keyword is better than creating these methods inside the Person object constructor itself.
This is because it creates a seperation between object properties and objects methods and results in cleaner, faster and more organized code.
This seperation is the standard method for ES5 and the preferred way for many developers.