JavaScript Object

Let's understand the JavaScript Object

As we know, JavaScript is an object-based scripting language for object oriented web applications. Similar to real-world objects, the objects in the JavaScript language also encapsulate various states and behaviors. The various states of an object are defined as its properties whereas the behaviors of the object are specified by its methods.

We know an Object Oriented Programming (OOP) language is based on:

  • Classes
  • Objects
  • 4 Principles:

    • Abstraction
    • Encapsulation
    • Inheritance
    • Polymorphism

JavaScript Object

If we use as an example a Dog then.

Object: Dog

The state of a dog: breed, weight, colour.

Behavior of the Dog: run [ run() ] and sit [ sit()]; here run() and sit() are the methods.

Let's understand how to create objects in JavaScript: in JavaScript we can create objects using one of the following two ways,

  1. By creating a direct instance
  2. By creating a function template

By Creating a direct Instance: In this method we use the "new" keyword. The syntax for this method is as in the following,

  1. Obj=new object();  
We can add properties and methods using a period (.) followed by a property or method name.

Example:
  1. Obj.name="Ankur";  
  2. Obj.age=22;  
  3. Obj.getValue();  
Here Obj is a newly created object, name and age are properties while getValue() is a method.

By creating function template: In this after defining a function template for an object, we need to create an instance of the object by using the "new" keyword. A function template for an object is created by using the "function" keyword, we can also add properties to the function template by using this keyword. The syntax is given below. 
  1. function bike(speed, engine, color)  
  2. {  
  3. this.speed=speed;  
  4. this.engine=engine;  
  5. this.color=color;  
Here the function named bike is created with the three parameters named speed, engine and color. The properties are assigned with properties that we want the bike object to have. The "this" keyword represents the current object that is in use.

Now we need to create an instance of the object bike by using the "new" keyword:

  1. var my_bike= new bike("120kph""V-6""Black");  
Now we can access the my_bike instance of the bike object:
  1. var engine_type= my_bike.engine;  
Let's do a little exercise in code.
JavaScript Object2

Here a function, employee, is created with three parameters, name, jobtitle and salary. Then an object, emp1, is created of the employee type using the "new" keyword and passing the new values of the created parameters.

JavaScript Object3

So this was a little bit about objects in JavaScript. We will learn more in the next article and do more live work in JavaScript Objects. 

Up Next
    Ebook Download
    View all
    Learn
    View all
    Foreantech - A complete online solution company.