JavaScript Object

By:    Updated: January 24,2017

Although instances of Object don't have much functionality, they are ideally suited to storing and transmitting data around an application.

JavaScript Object Creation

There are some ways to explicitly create an instance of Object.

<script type="text/javascript">
//using new operator
var site1 = new Object();
site1.name = "valinv";
site1.developer = "flasle";

//using object literal notation
var site2 = {
	//expression context start
	name: "valinv",
	developer: "flasle"
	//expression context end
};

//other ways, such as json object
var site3 = {};
site3.name = "valinv";
site3.developer = "flasle";
</script>

Developers(also including me) tend to favor object literal notation, because it requires less code and visually encapsulates all related data.

Access JavaScript Object Properties

There are two approaches to access object properties.One is dot notation, the other is bracket notation.Functionally, there is no difference between the two approaches.But there are two main advantages that it allows you to use variables for property access and allows properties contain non alphanumeric characters when using bracket notation.

<script type="text/javascript">
var site2 = {
    name: "valinv",
    developer: "flasle",
    "sub site": "www"
};

alert(site2.name); //dot notation
alert(site2["name"]); //bracket notation

var developer_property_name = "developer";
//use variables for property access
alert(site2[developer_property_name]);

//property contains non alphanumeric characters, here is a space in it
alert(site2["sub site"]);
</script>
More in Development Center
New on Valinv
Related Articles
Sponsored Links