One-Off Objects
In 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access