Object-Oriented JavaScript: An Introduction to Core Concepts
JavaScript is a powerful object-oriented language whose capability has frequently been underestimated when compared with other OO languages. This article, the first of several parts, should help you gain a better understanding of JavaScript's true value. It will show you the basics of creating custom objects and defining their methods and properties. You will also learn some advanced concepts such as Inheritance. Plenty of real-world examples will be included.
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:
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.