Tech Junkie Blog: JavaScript Objects Deep Dive : Creating Objects With The new Keyword

Thursday, April 27, 2017

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.

2 comments:

  1. Al Safar Cleaning Company is one of the best cleaning شركة الصفرات لعزل الاسطح بالرياض companies in Riyadh. We always strive to be the best general cleaning company in Riyadh. We also provide the best cleaning and cleaning services that you may get. Therefore, شركة الصفرات للتنظيف بالرياض our company works to provide all the means شركة الصفرات لرش المبيدات بالرياض to meet our customer service and maintain leadership and quality. The service is continuous as the company شركة الصفرات لنقل الاثاث بالرياضoffers the best of its services in the field شركة الصفرات لكشف تسربات المياه بالرياضof cleaning and it is one of the most important characteristic of us because our company is characterized شركة الصفرات لتنظيف الخزانات بالرياضby honesty, accuracy and speed in the completion of the tasks required of them in the fullest possible.
    The company is one of the most professional شركة الصفرات لمكافحة الحشرات بالرياضand leading companies in the field of cleaning houses. We provide all cleaning services by cleaning houses, houses, apartments, villas, etc. Our company is one of شركة الصفرات لتسليك المجارى بالرياض the best companies in the field of cleaning in Riyadh. We also use the best non-harmful and odorless cleaning materials to maintain your health.

    ReplyDelete