Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript expando objects

What are expando objects in javascripts?

For what purpose we need this ? Any complete example will be appreciated

I found 1 article here Javascript: The red-headed stepchild of web development

like image 693
xyz Avatar asked Mar 24 '10 07:03

xyz


People also ask

What is an expando property?

An expando property is a custom property. By default, all common browsers support adding arbitrary properties to any object, but only Internet Explorer allows switching it off. With the expando property of the document, you can set or retrieve whether custom property support is enabled.

What is Expando?

Cracking agent for rock & concrete breaking solution. EXPANDO is an expansive mortar chemical that cracks rocks and concrete, without using explosives. It is a concrete cutting, granite breaking and general demolition solution.


2 Answers

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.

like image 105
David Hedlund Avatar answered Oct 02 '22 11:10

David Hedlund


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 
like image 32
Abhijit Avatar answered Oct 02 '22 12:10

Abhijit