We know an Object Oriented Programming (OOP) language is based on:
- 4 Principles:
If we use as an example a Dog then.
The state of a dog: breed, weight, color.
- Behavior of the Dog: run [ run() ] and sit [ sit()]; here run() and sit() are the methods.
- 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.
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)
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.