How to access a function property as a method in JavaScript?

JavascriptObject Oriented ProgrammingProgramming

Accessing a function as a method

 A javascript object is made up of properties. To access a property as a method, just define a function to a property and include other properties in that function.

In the following example an object called "employee" is created with properties "fullName", "lastName" , "firstName" and "id". A function is defined under property "fullName" and properties such as "firstName" and "lastName" were included in it. So when the property "fullName" is called, the full name of the employee is going to display as shown in the output.

Example-1

Live Demo

<html>
<body>
<script type="text/javascript">
   var employee = {
      firstName: "raju",
      lastName : "nayak",
      Designation : "Engineer",
      fullName : function() {
         return this.firstName + " " + this.lastName;
      }
   };
   document.write(employee.fullName());
</script>
</body>
</html>

output

raju nayak

Example-2

Live Demo

<html>
<body>
<script type="text/javascript">
   var student= {
      Name: "susan",
      country : "USA",
      RollNo : "5",
      details : function() {
         return "the student named" + " " + this.Name + " " +"is allocated with rollno " + " " +              this.RollNo ;
      }
   };
   document.write(student.details());
</script>
</body>
</html>

output

the student named susan is allocated with rollno 5
raja
Published on 21-Jun-2019 14:47:27
Advertisements