In JavaScript, there are four methods to use to create an object:

  1. Object literals
  2. New operator or constructor
  3. Object.create method
  4. Class

In this post, we will learn each of these methods.

Object literals

An object literal, also called an object initializer, is a comma-separated set of paired names and values. You can create an object literal as shown below:

You can add properties dynamically in an object, including after you have created the object. Here we add the dynamic property car.type:

The object literal is a simple expression that creates an object each time the statement that it appears in is executed in the code. You can also use Object.defineProperty to create properties in the object literal as shown below:

The main advantage of using Object.defineProperty is that you can set values for object property descriptors or modify existing properties. You can learn more about Object Property Descriptor here.

New Operator or Constructor

The second way to create an object is to use the constructor function. If you call a function using a new operator, the function acts as a constructor and returns an object. Consider the following code:

Learn full article on the Infragistics blog

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s