Tech Junkie Blog - Real World Tutorials, Happy Coding!: JavaScript Objects Deep Dive : Creating Objects With The new Keyword

Thursday, November 4, 2021

JavaScript Objects Deep Dive : Creating Objects With The new Keyword

In the previous post we visited how to create an object with an object literal.  In this post we are going to create the same object using the new keyword.  When creating objects using the new keyword it is required that the it is followed by a function call.  The purpose of this function call is the needs a way to call to the constructor of the new object.  A constructor is used to create or initialize the created object.

Here is the code to rewrite our literal object using the new keyword:

var product = new Object();

product.name = "Chai";
product.category= "Tea";
product.country= "India";
product.supplier= {
    name: "ACME Tea Of India",
    location: "New Delhi"
};

product.related = new Array("Earl Grey", "Green Tea", "Dark Tea", "White Tea");
product.display = function () {
    console.log(this);
};


























Notice the object is the same as the object we created using the literal syntax but with the new keyword.  Also we've created a custom object with the line

var product = new Object();

But we've also created a native object with the line:

product.related = new Array("Earl Grey", "Green Tea", "Dark Tea", "White Tea");

So the new keyword can be used to create both a custom object and a native object.




1 comment:

Search This Blog