Nested Object Literal and Making Function as Object
It is a simple task to define an Object Literal. For example:
var myObject = { property: "Foo: Bar", oFnc: function(){ document.writeln("Hello World!"); } };
As you can see, myObject is now playing as an object. To check on it, just run this line of code:
alert("myObject is: " + typeof myObject);
And, it will tell you myObject is an ‘object’, as follows:
So, to access its property/function, we can basically call it as simple as this:
To access property and display it in alert prompt:
alert(myObject.property);
To access function, we can do it like this:
myObject.oFnc();
OK now, I wanted to add another group of Object Literal, say put it in oFnc function and then return it. So the complete code will look something like this:
var myObject = { property: "Foo: Bar", oFnc: function(){ document.writeln("Hello World!"); //additional object literal var nestOL = { nProperty: "Bar: Foo", nFnc: function(){ return alert("Hello World! in alert prompt!"); } }; return nestOL; } };
Since I’m returning an object-literal from the oFnc function, it causes oFnc to act as function, but aslo an object when it’s called. To check it’s function and also, an object when it’s invoked, just run code as follows:
alert("oFnc is: " + typeof myObject.oFnc); alert("oFnc() is: " + typeof myObject.oFnc());
And you will get the respective results shown in these following screen-shots:
oFnc is a function:
oFnc() is an object when called:
Well, everything is so clear with what we have. Now, we can easily to access the properties/functions on the fly. From the example above, we basically have a nested Object Literal (so-called) and also, defined a ‘function’ object which is oFnc. For instance, I wanted to display ‘Hello Word!’ in HTML element and followed by ‘Hello World! in alert prompt!’ in an alert prompt, here is what I do:
myObject.oFnc().nFnc();
Once the line of code is run, it yields the result as follows:
The advantage:
We can make a function to act as function, yet an object as well whenever it’s called. Besides of this, we can also add the private properties/functions into the defined function, too. This will produce and mimic a ‘chaining’ method. In addition, we are doing several tasks at once by calling a single line of code. Enjoy!
No related posts.





[...] See more here: Boris Ding P H | PHP . JavaScript . Ajax [...]