Javascript expando objects

↘锁芯ラ 提交于 2019-11-27 11:12:16

Well, in javascript, any object is an expando object. What it means is, as the article covers, that whenever you try to access a property1 it will automatically be created.

var myObj = {}; // completely empty object
myObj.myProp = 'value';

The moment you assign myProp a value, the property myProp is dynamically created, eventhough it didn't exist before. In a lot of other languages, such as C#, this is not normally possible (actually C# has just enabled expando object support as well, but that's besides the point). To access a property in a normal class in C#, you need to specify in the class that it does indeed have this property.

1 Not quite correct. See npup's comment below for clarification.

Abhijit

Everything except primitive types(string, number,boolean) are objects and support Key:values structure. properties(keys) can be accessed and set using the dot notation as well as the square brackets.

var myObj = {};   
myObj.myProp1 = 'value1'; //works, an expando property   
myObj[myProp2] = 'value2'; // doesn't work, myProp2 is an undefined name.
myObj['myProp2'] = 'value2'; // works  , an expando property   
myObj[2010]= 'value'; //note the key is number, still works, an expando property??   
myObj.2010 = 'value'; // FAILS. to use dot notation, key must be a string

An article written in 2007 that uses document.all (as the only way to access elements)? That's a big red flag.

It is just dressing up "You can add properties to an object" with some buzzwords.

We need to be able to do this because otherwise we wouldn't be able to store data, and that would make JavaScript a pretty useless language.

(Everything is an array? No it isn't. And it iterates over an object without a hasOwnProperty wrapper. That isn't safe. Just keep away from the article, it is worse than useless)

JavaScript turns elements with specific IDs of names into expandos of the returned DOM object. It is explained here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!