Object-Oriented JavaScript: An Introduction to Core Concepts - Coupling methods to objects: defining self-contained constructors
(Page 3 of 5 )
As the term suggests, self-contained constructors are simply regular constructors that contain, or include inside their structure, the definition for all the methods of the pertinent object. Returning to the example you saw earlier, the constructor for “Div” objects might be rewritten as follows:
function Div(w,h,t,l,p,bg){
// define object properties
this.div=document.createElement('div');
this.w=w+'px';
this.h=h+'px';
this.pos='absolute';
this.top=t+'px';
this.left=l+'px';
this.pad=p+'px';
this.bord='1px solid #000';
this.bg='#'+bg;
// define 'display()' method
this.display=function(){
this.div.style.width=this.w;
this.div.style.height=this.h;
this.div.style.position=this.pos;
this.div.style.top=this.top;
this.div.style.left=this.left;
this.div.style.padding=this.pad;
this.div.style.border=this.bord;
this.div.style.background=this.bg;
document.getElementsByTagName('body')[0].appendChild(this.div);
}
}
Now, the constructor shows a slightly more compact structure, since all the properties, along with the definition for the “display()” method, are placed inside of its context. As you can appreciate, the above used syntax makes it easier to see at first glance what methods are exposed by the corresponding object. Of course, this notation doesn’t imply changing the way that objects are instantiated, therefore, if I wanted to spawn another “Div” object, I’d use the same syntax that you previously learned:
var div=new Div(300,250,100,100,5,'00f');
div.display();
As shown above, spawning user-defined objects in JavaScript isn’t very different from other programming languages. Once the constructor has been defined, an object can be instantiated with the “new” keyword and assigned to a regular JavaScript variable.
Now that you know how a self-contained constructor looks and works, it’s time to take a look at another interesting topic of object-based JavaScript: the “Function” object. Just scroll down the page and keep reading.
Next: Functions and objects: a closer look at the “Function” object >>
More JavaScript Articles
More By Alejandro Gervasio