Declaration and Initialization of object in javascript

Posted By : Vinay Tiwari | 19-Sep-2018

In JavaScript, there are two different ways to make an object: constructor function and literal notation. Take a look below:

 
// constructor function
function Website() {};

// literal notation
var Website = {};
 

Whichever way you have quite recently made a JavaScript question called Website. The fundamental distinction here is the thing that you can do with it. With the constructor function notation, you make an object that can be instantiated into various instances (with the new keyword), while the literal notation conveys a single object, similar to a singleton.

 

Defining methods and properties

 

Objects in JavaScript have strategies and properties, regardless of whether they are worked with the constructor function or with the literal notation. How about we perceive how to characterize them:

 
// constructor function
function Website() {
    this.url = 'http://www.gmail.com';
    this.printUrl = function() {
        console.log(this.url);
    };
};

// literal notation
var Website = {
    'url': 'http://www.gmail.com',
    'printUrl': function() {
        console.log(this.url);
    }
};
 

Using the objects

 

Other than the language structure, the two articles vary by the way you utilize them. On the off chance that the question has been made with the constructor function, you should instantiate it first. Then again the literal-notated one is prepared for utilizing:

 
// constructor function
var InternalPointers = new Website();
InternalPointers.printUrl();

// literal notation
Website.printUrl();
 

Instantiation versus singleton approach

 

The past piece uncovers another critical property: with the constructor function you can instantiate what number of objects you need, and they will be all novel. With the literal notation you generally manage the object (which is a singleton, recall?), regardless of whether you characterize another variable with the protest as esteem:

 
// literal notation
var original = { 
    'property' : 'original' 
}

console.log(original.property); // 'original'

var clone = original;
clone.property = 'clone';

console.log(original.property); // 'clone'
 

Thanks

 

About Author

Author Image
Vinay Tiwari

Vinay is a bright UI developer, having knowledge of HTML, CSS, Bootstrap, Jquery and AngularJs. His hobbies are interacting with people, listening music etc.

Request for Proposal

Name is required

Comment is required

Sending message..