HTML and CSS Reference
In-Depth Information
So should you use immediate functions or immediate objects? That's mostly up to you, but it
ultimately boils down to how complex your code is (or that you anticipate it's going to become).
For very complex tasks, an immediate object is perhaps preferable because it allows you define
properties and split implementation into multiple methods. An immediate function is something
simpler that works well for any code expressed as a plain sequence of statements.
extending existing objects with behavior
Earlier, this chapter discussed how properties can be added to an object's prototype so that each new
instance of that object is augmented with those new properties. Nearly the same considerations can
be made for functions, which can be used to augment an existing object definition with behavior.
As an example, consider the Number object again. The following code shows how to add a new
random member that returns a random number greater than the specified minimum.
// This code needs to run once--so we add it as an immediate function.
(if (typeof Number.prototype.random === 'undefined') {
Number.prototype.random = function(min) {
var n = min + Math.floor(Math.random() * 1000);
return n;
};
}());
After this code has run once, you are free to use the following function:
function doWork() {
var n1 = new Number().random(0);
var n2 = new Number().random(10);
alert("Numbers are " + n1 + " and " + n2);
}
Note Augmenting the prototype of native objects is considered a bad practice because it
makes the code less predictable and may hurt maintainability. This consideration, though,
applies mostly to team development. If you're writing code for yourself, this point is less
important.
Constructor functions
As mentioned earlier, there are two main reasons for using functions: defining repeatable behavior
and creating custom objects. Here, you'll tackle the second scenario, starting with a look at the
following code:
var Dog = function(name) {
this.name = name;
this.bark = function() {
Search WWH ::




Custom Search