Objects, like arrays, are used to store information; however, they can be used to also store functionality. When a value is stored in an object, it is referred to as a property. When functionality is embedded in an object, it is called a method. This recipe shows how to use properties and methods of objects in MooTools.
An object is a reusable, client-side, storage syntax. In other words, it's like a function because we can call it from anywhere, but it is also like a miniature, temporary database, too!
Note
We can make a parallelism between instances of an object and rows of a database. That imagery can be furthered by likening columns, fields of the row, to properties of the object.
In raw JavaScript, one way to add a property to an object is with the dot operator like this: my_object.name = 'Jay LG Johnston'
;. Unfortunately, that does not allow us to reuse the object. In other words, if our code was used in another place, we would have to copy and paste the entire block.
Defining built-in functions, called methods on this kind of singleton class is possible, but our storage mechanism will only ever hold one row, at any given time. Our code in the singleton could not be used without copying and pasting it to other singleton objects. More explanation follows.
Instead of creating our object as a single instance, we create a template object using the MooTools Class object. This abstraction allows us to use a more familiar syntax for creating our objects.
<script type="text/javascript" src="mootools-1.3.0.js"></script> </head> <body> Hello Bulletin Board:<br/> <div id="hello_board"></div> <script type="text/javascript"> var hb = $('hello_board'); var my_object = new Class({ // object constructor initialize: function(oldies_array){ this.oldies = oldies_array; }, // object method say_hello: function() { this.oldies.each( function(oldie, index){ hb.set('html',hb.get('html')+'<br/>Hello '+oldie+', you are number '+index+' on the playlist!'); } ); hb.set('html',hb.get('html')+'<br/>'); } }); var oldies = ['Stevie Wonder', 'a lot of Bob Dylan', 'a lot of Rolling Stones', 'a lot of Miles Davis', 'John Coltrane']; var obama = new my_object(oldies); obama.say_hello(); var oldies = ['George Thorogood', 'Dennis DeYoung', 'The Cyrkle']; var other = new my_object(oldies); other.say_hello(); </script>
When we have a tiny storage mechanism to store our values with simple syntax, we can call internal methods on each instance of a templated object. Through code reuse like this, we can really bring value to our employers.
This sort of code reuse is a feature of Object Oriented Programming (OOP). Let us now update our resumes for we know the basics of code reuse and must proclaim our ability to add value in the workplace.
The search engines have links to Wikipedia articles describing different design patterns in the OOP world. Knowing more about those patterns not only makes our code better but prepares us for those pesky interview questions.