Tuesday, May 23, 2017

JavaScript Objects

Hi everyone, Today we are going to discuss about objects of JavaScript.
JavaScript is an object based programming language. So, everything in JavaScript is an object. A JavaScript object is an entity which have properties and methods.

There are 3 ways to create objects in JavaScript. Let's look at these methods one by one with examples.
  1. By object literal
  2. By creating instance of object
  3. By using a constructor

By object literal

Syntax
object_name = {property1 : value1 , property2 : value2, ...}

Let's look at an example and try to understand it. 

Example 1

Figure 1

In here, we create an object named 'employee'. There are 3 properties for this object, they are id, name and age. We assign values for each of this property. To access the property of object we must use, 
object_name.property
Try to access by simply using property without object name will not be work. You can try it and watch the result.
Here is the result we got.
Figure 2

In the result, id, name and age of employee is shown.

By creating instance of object
In here, we create an object using new keyword.

Syntax
var object_name = new Object();

Example 2
Figure 3

In here, we first declared an object. Then we add properties to object as 
                                               object_name.property = property value 

Here is the result.
Figure 4
As you can see, we got the same result as previous example.

By using a constructor

First we look at what constructor is. A constructor is a special method of a class or structure in object-oriented programming that initializes an object of that type. It can be used to set the values of the members of an object, either to default or to user-defined values. JavaScript provides a special constructor function called Object() to build the object.

In here, we create a function with arguments, each argument value can be assigned in the current object by using 'this' keyword. In here, this keyword refers to the current object.

Syntax
function object_name(parameter1, parameter2){
this.parameter1 = parameter1;
this.parameter2 = parameter2;
}

Let's look at the example and try to figure it out.

Example 3
Figure 5

In here, we create a function called 'employee' and properties are included as parameters of function. The result we got is same as previous examples.

Figure 6

Defining methods of an object
To do this, we have to add property in the function with same name as method.

Example 4
Figure 7

In here we add a property called changeAge in function 'employee'. Also there is a method in same name. We can change age by using changeAge method. We can do it as follows.
object_name.property(property_value);
So, in our example, it is as follows.
emp.changeAge(35);
Figure 8 shows the output we got.

Figure 8

Hope you'll get a better understand about objects. Thank you for watching this tutorial.

No comments:

Post a Comment