Different ways to create an object in javascript
JavaScript is a very flexible object-oriented language when it comes to syntax.
In this article, we will see different ways to create an object in JavaScript. JavaScript is a class-less language so we use functions as a class. This is one of the easiest ways to instantiate an object in JavaScript.
(1) Creating an object using a function as a class
<script>
// Function acting as a Class.
function myFunction(car, price) {
this.car= car;
this.price = price;
this.carInfo= function() {
console.log(this.car);
console.log(this.price);
}
}
// Creating the object of copyClass
// and initializing the parameters.
var obj = new copyClass("Volvo", 200000);
// Calling the method of copyClass.
obj.carInfo();
</script>
Output:
Volvo 200000
Explanation:
There are two parameters, car and price ( the 'this' keyword is used to differentiate the car and price of the class to the car and price of the arguments that are being supplied.) and a method carInfo that prints the value of these parameters. We then simply create an object obj of the copyClass, initialize it and call its method.
(2) Creating an object using object literals
Literals are smaller and simpler ways to define objects. Below we instantiate an object exactly the same as the previous one just with the object literal.
<script>
// Creating Object.
var obj = {
car : "",
price : "",
carInfo : function() {
console.log(this.car);
console.log(this.price);
}
}
// Initializing the parameters.
obj.car = "Volvo";
obj.age = 200000;
// Using method of the object.
obj.carInfo();
</script>
Output:
Explanation:
Volvo 200000
Explanation:
This method works the same as the previous one but instead of bundling the parameters ( car and price ) and the method ( carInfo ) inside of a function, we bundle them in the object itself, initialize the object and simply use the methods.
(3) Creating an object singleton using a function
This way is a combination of the first two ways which we have already seen earlier. Here we can use a function to define a singleton object.
<script>
// Creating singleton object.
var obj = new function() {
this.car = "";
this.price = "";
this.carInfo = function() {
console.log(this.car);
console.log(this.price);
};
}
// Initializing object.
obj.car = "Volvo";
obj.price = 200000;
// Calling method of the object.
obj.carInfo();
</script>
Output:
Volvo 200000
Explanation:
No comments:
Post a Comment