Object Initializer

JavaScript has number of predefined objects and can also create our own objects. object cane be created using object initializer.

Object Initializer :

Objects can be initialized using new Object(), Object.create() or using initializer notation. It is a comma delimited list of zero or more pairs of property names and associated values of an object, which are be defined in curly braces ({}).

syntax :

var data = {};

var data = {a:'hello',b:42,c:{}};

var a = 'hello', b = 42, c = {};
var data = {a:a,b:b,c:c};

var newData = {
         property: function ([parameters]) {},
         get property() {},
         set property(value) {}
};

where as In ECMAScript 2015, these notations are defined as :

var a = 'hello', b = 42, c = {};
var data = {a,b,c};

var a = {
      property([parameters]){}
};

var prop = 'zoo';

var a = {
     [prop]: 'hello',
     ['b' + 'ut']: 'here'
};

values of the object properties can contain primitive datatypes or other objects.

Creating objects :

An empty object with no properties can be created as :

var emptyObject = {};

The main advantage of this notation intializer is we can create objects quickly with its properties inside curly braces. You can simply notate a key : value pairs which are been separated by comma.

Example :

var details = {
name : 'ram',
age : 20,
college:'srichaitanya'
}

Accessing Properties :

Once the object is defined we might want to retrieve them or change them. Object properties can be accessed using dot notation or bracket notation.

details.name; //ram
details['age'] //20

details.name = 'tommy';

Duplicate property name :

when the same name is used for the property, then the second property is overwritten by the first value.

Example :

var z = {x:1,x:2};

console.log(z); //  x : 2

In ECMAScript 5, if duplicate elements are defined then it would be considered as syntax error.In ECMAScript 2015 has removed this restriction. By using strict mode, it would allow the duplicate property names.

Method Definitions :

A property of an object can refer to a function or getter or setter method.

var example = {
property : function([params]){}
get property() {},
set property(val) {}
};

Spread Properties :

It copies own enumerable properties from a provided object into a new object.

Example :

var obj1 = { foo: 'bar', x: 42 };

var obj = { ...obj1 };

console.log(obj);
// { foo: 'bar', x: 42 }

No comments:

Post a Comment

Overview of AngularJS

AngularJS is an open source web application framework. It is now maintained by Google . The most of the code can be eliminated by using th...