Methods in Constructor Functions
This lesson teaches how to define and add new methods in a constructor function.
We'll cover the following...
Defining Methods
Methods are defined differently in the constructor functions.
Example
We defined our methods inside the object literals in the following way:
Press + to interact
//creating an object named employeevar employee = {//defining properties of the object//setting data valuesname : 'Joe',age : 28,designation : 'Developer',//function to display name of the employeedisplayName() {console.log("Name is:", this.name)}}//calling the methodemployee.displayName()
Now, let’s write the same function but for the constructor function this time:
Press + to interact
//creating an object named Employeefunction Employee(_name,_age,_designation) {this.name = _name,this.age = _age,this.designation = _designation,//function to display name of the Employeethis.displayName = function() {console.log("Name is:", this.name)}}//creating an objectvar employeeObj = new Employee('Joe',22,'Developer')//calling the method for employeeObjemployeeObj.displayName()
...
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy