Object-Oriented JavaScript: An Introduction to Core Concepts - Functions and objects: a closer look at the “Function” object
(Page 4 of 5 )
A less-known concept in JavaScript is that each function is itself an object. The reason for this rests on the automatic creation of a “Function” object each time a regular function is defined, without specifying the “new” keyword, as one would expect to do with conventional objects. To understand this concept, have a look at the example below, which creates a “Div” function, and then adds some properties to the “Function” object:
function Div(){}
Div.w='400px';
Div.h='300px';
Div.pos='absolute';
Div.top='20px';
Div.left='20px';
Div.pad='5px';
Div.bord='1px solid #000';
Div.bg='#ff0';
// define 'display()' method
Div.display=function(){
var div=document.createElement('div');
div.style.width=Div.w;
div.style.height=Div.h;
div.style.position=Div.pos;
div.style.top=Div.top;
div.style.left=Div.left;
div.style.padding=Div.pad;
div.style.border=Div.bord;
div.style.background=Div.bg;
document.getElementsByTagName('body')[0].appendChild(div);
}
In the example above, I’ve defined a “Div()” function, which automatically has created a “Function” object. Provided that an object has some properties and methods, what I’ve done is simply assign a few properties to this “Div” object, in addition to the “display()” method. Finally, the method can be called up as you’d do normally with a regular object, as following:
Div.display();
Even when the “Function” object actually isn’t very popular, and certainly isn’t used very frequently in JavaScript applications, the above example demonstrates the basics of how to use it appropriately in your scripts.
After having explained some of the key points regarding the unusual “Function” object, let’s move on and continue learning more about user-defined objects in JavaScript. In this case we will take a look at the “constructor” property. Want to know more? Right, let’s explore this topic together.
Next: Getting information about objects: looking at the “constructor” property >>
More JavaScript Articles
More By Alejandro Gervasio