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:
If we use as an example a Dog then.
-
Object: Dog
-
The state of a dog: breed, weight, color.
- 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,
- By creating a direct instance
- By creating a function template
Creating a direct Instance: In this method, we use the "new" keyword. The syntax for this method is as in the following,
We can add properties and methods using a period (.) followed by a property or method name.
Example
- Obj.name="Ankur";
- Obj.age=22;
- Obj.getValue();
Here Obj is a newly created object, name and age are properties while getValue() is a method.
By creating a 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.
- function bike(speed, engine, color)
- {
- this.speed=speed;
- this.engine=engine;
- 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 having. 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:
- var my_bike= new bike("120kph", "V-6", "Black");
Now we can access the my_bike instance of the bike object:
- var engine_type= my_bike.engine;
Let's do a little exercise in code.
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.
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.