代码改变世界

How to access the properties of an object in Javascript

2014-07-23 14:52  wildboar  阅读(225)  评论(0编辑  收藏  举报

Javascript has three different kinds of properties: named data property, named accessor property and internal property. There are two kinds of access for named properties: get and put, corresponding to retrieval and assignment, respectively. Please refer to the Ecma-262.pdf.

Here are the ways of accessing named data property.

1 var obj = {
2 
3     property_1: 123
4 
5 };

You can get its value like the following:

1 obj.property_1;

Or

obj[“property_1”]; //please note, quote is required here

but you have to use [“xxx”] if you intend to use for/in to access the properties of an object

1 for(p in obj)
2 {
3     alert(obj[p]);
4 }

The system will alert undefined if you access like the following within the for/in, the reason is javascript pass the property as string

for (p in obj)
{
    alert(obj.p);
}