Search⌘ K

Methods in Constructor Functions

Explore how to define and add methods within JavaScript constructor functions using the 'this' keyword. Understand the difference between methods in object literals and constructors, and how to ensure methods apply to all created objects.

Defining Methods

Methods are defined differently in constructor functions.

Example

We defined our methods inside object literals in the following way:

Javascript (babel-node)
//creating an object named employee
var employee = {
//defining properties of the object
//setting data values
name : 'Joe',
age : 28,
designation : 'Developer',
//function to display name of the employee
displayName() {
console.log("Name is:", this.name)
}
}
//calling the method
employee.displayName()

Now, let’s write the same function but for the constructor function this time:

Javascript (babel-node)
//creating an object named Employee
function Employee(_name,_age,_designation) {
this.name = _name,
this.age = _age,
this.designation = _designation,
//function to display name of the Employee
this.displayName = function() {
console.log("Name is:", this.name)
}
}
//creating an object
var employeeObj = new Employee('Joe',22,'Developer')
//calling the method for employeeObj
employeeObj.displayName()

Explanation

In line 9 of the code for object literal, the method declaration was simple: the name of the function followed by ...