Saturday 1 September 2018

JavaScript: Adding methods to an object

An object in JavaScript has properties and methods associated with it. For example, see the following object 'employee', it has properties firstName, lastName and id. It has methods
a.   setFirstName : sets the firstName of employee object
b.   setLastName : sets the lastName of employee object
c.   setId : sets the id of the employee object
d.   getDetails : return string representation of employee object.

var employee = {
 firstName: "no_name",
 lastName: "no_name",
 id: "-1",
    
 setFirstName: function(firstName){
  this.firstName = firstName;
 },
   
 setLastName: function(lastName){
  this.lastName = lastName;
 },
    
 setId: function(id){
  this.id = id;
 },
    
 getDetails: function(){
  return "[firstName = " + this.firstName + ", lastName = " + this.lastName + ", id = " + this.id + "]";
 }
}

Note that I used this keyword inside the methods, When a function is called from the object, this becomes a reference to the current object. By using this, we can refer current object properties.

object.html

<!DOCTYPE html>

<html>

<head>
    <title>objects</title>
</head>

<body>
    <script type="text/javascript">
        var employee = {
            firstName: "no_name",
            lastName: "no_name",
            id: "-1",

            setFirstName: function(firstName) {
                this.firstName = firstName;
            },

            setLastName: function(lastName) {
                this.lastName = lastName;
            },

            setId: function(id) {
                this.id = id;
            },

            getDetails: function() {
                return "[firstName = " + this.firstName + ", lastName = " + this.lastName + ", id = " + this.id + "]";
            }
        }

        employee.setFirstName("Hari Krishna");
        employee.setLastName("Gurram");
        employee.setId(1);

        document.write(employee.getDetails());
    </script>
</body>

</html>

Load above html in browser, you can able to see following text.

[firstName = Hari Krishna, lastName = Gurram, id = 1]


Previous                                                 Next                                                 Home

No comments:

Post a Comment