Pages

Monday, September 12, 2016

Object Creation in Javascript

In Javascript, we don't have classes. Instead we use functions. There are two ways to create custom objects.

1. Constructor function
2. Literal Notation

1. Creating an object using constructor function;
        In this method, we first create a function and then create an object using that function.

function Employee(firstName, lastName){
      this.firstName = firstName;
      this.lastName = lastName;

      this.getFullName = function(){
            return this.firstName + " " + this.lastName;
      }
}

var employee = new Employee("Hello","World");

Here, employee is the object and Employee is the constructor function.


2. Literal Notation:

 var employee = {
        firstName : "Hello",
        lastName : "World",
        getFullName : function () {
                      return this.firstName + " " + this.lastName;
        }
}

        document.write("FirstName = " + employee.firstName + "[br/]");
        document.write("LastName = " + employee.lastName + "[br/]");
        document.write("FullName = " + employee.getFullName() ;

In this method, we already have the object. Here, employee is the object name. So, we can access the properties using that object name. Objects created using this method are singletons i.e. any changes to one instance affects the entire script.

No comments:

Post a Comment