11.5. One-Off ObjectsIn most cases, the power of OO-based development is being able to create instances of an object for various purposes. However, sometimes all you need is one object. The Prototype Ajax library uses these one-off objects quite a bit. One way to create a one-off object is to create an associative array of properties and methods and assign the lot to a variable. Any of the following create the same object, with the same behavior; each just uses a different syntax: var oneOff = { variablea : "valuea", variableb : "valueb". method : function ( ) { return this["variablea"] + " " + this["variableb"]; } } All objects are functions, and all functions are objects in JavaScript. In this case, the object is an associative array with two properties and a method. Because the method is a function and an object, it can be added to the array just like any other static item. To access the members, the method uses named-array notation, but outside the object, it uses standard property access: alert(oneOff.variablea); alert(oneOff.method( )); Another approach is the following: var oneOff = new Object( ); oneOff.variablea = "valuea"; oneOff.variableb = "valueb"; oneOff.method = function ( ) { return this.variablea + " " + this.variableb; }; You can construct a new object from the actual Object, and then add properties and methods to the object instance. You don't use prototype, because you're not adding new properties or methods to an underlying object. You're adding them to an object instance directly. The method accesses the parent object's other properties using this and just provides a named property. Here's how to access the properties: alert(oneOff2.variableb); alert(oneOff2.method( )); The last approach we'll investigate uses our old function to create an object, but this time, we're assigning it directly to a variable and using it as a one-off: var oneOff = new function( ) { this.variablea = "variablea"; this.variableb = "variableb"; this.method = function ( ) { return this.variablea + " " + this.variableb; } } Again, there's no difference in how the object properties are accessed. You can use a one-off object when you need to encapsulate a group of methods and properties into one object, and then reuse this object throughout your entire application. You don't need many instances of the objectjust one.
|