2007-09-06
| Rate This Article: | Add This Article To: |
Once you understand just how prevalent objects are in JavaScript, you can start to do some pretty powerful things. In this week's installment on JavaScript programming, I show you how you can extend the built in objects in JavaScript.
The built-in Function object
This is where things get really bizarre and cool. Let's take a step backwards. We created objects by using the new keyword and a function. In such a context, the function behaves as a constructor, giving us an object-oriented feature.
But what about when you create a function? Look at this simple code:
function SomeFunction() {
alert('hi');
}
This is just a simple function that displays an alert. But when these three lines of code run, the JavaScript runtime creates a new function object. Does JavaScript use some other object that serves as a constructor for this function object?
Yup. And it's called the Function object.
Make sure you recognize how the language processes its code. The function declaration is itself a statement. When JavaScript encounters the function declaration, JavaScript processes the code by creating a function object. (This is not the same as a running the function's code, of course.) The JavaScript processor sees the function declaration, and creates a new object that is based on yet another object, the internal Function object.
Try this and you'll see what I mean:
alert(Function)
This code does not require any previous code to run; Function is a built in object that is itself a constructor function. The object is named Function and it has its own prototype just like any other function object.
That means when you create a function object, your function object inherits members from the Function object's prototype.
If you've stayed with me this long, you'll probably want to start exploring the official standard document, as this is the definitive guide on JavaScript. However, the official name is not JavaScript; it's ECMAScript. You can download the official specification here .
Inside the standards document, you can find information about the built in objects. This is where things might get confusing if you don't totally understand the object mechanism. Inside the specification, you'll find, for example, a description of the Function object in Section 15.3. This is referring to the Function object itself, not to functions in general! If you're not familiar with how the object mechanism works, the description could get confusing (as it did for me when I first started learning the language some time back). But in Section 13, you'll find a description of how to create "function objects." Function objects are just functions. Again, a solid understanding of the object mechanism pays off here.
So what can you do with the built-in Function object? The Function object has its own prototype, which you are free to extend by adding your own methods and data. When you do, then each of your own functions (as objects) will "inherit" these methods and data.
But be careful and keep it straight: It is your function objects that are inheriting these new members, not the objects you create when you call your functions as constructors. Got that? (I had to read that over a couple times just to make sure I said it right!)
The following code shows how you can extend the built-in Function object. This code isn't particularly useful, but it's short and sweet, and it demonstrates the technique:
// Extend the Function object
Function.prototype.getInfo = function() {
alert(this);
}
// Create a new function
function testfunc1(a) {
alert('My function');
}
testfunc1.getInfo();
The first part extends the built-in Function object by adding a getInfo function to the prototype. The next part declares a function, which creates a new function object. The final line demonstrates that the extension is present by calling the new function object's getInfo method that was inherited from the built-in Function object's prototype. (You can explore the web and explore this mechanism yourself to see how useful this can actually be.)
Arrays and Lists as Objects
Now let's move on to arrays and lists in JavaScript. Much of what you know about function objects applies here as well: When you create an array, you are creating a new object based on the prototype of a built-in Array object.
Arrays in JavaScript are easy to construct. This code creates a new array containing three members:
myarray = [10,20,30]
The JavaScript specification has a description of the Array object in section 15.4. This, of course, refers to the built-in Array object. However, farther down, in 15.4.4, is a description of the Array.prototype object. This is where you'll find the members that your own arrays will inherit, due to the nature of prototypes.
For example, one member is a function called reverse. That means your array has a reverse function available to it. Try it:
myarray.reverse(); alert(myarray);
You can see in the resulting alert box that the elements are reversed.
The spec contains other functions: toString, toLocaleString, concat, join, pop, push, shift, slice, sort, splice, and unshift. Notably missing, however, is a function to test whether the array contains an element.
So let's add it! If done correctly (by adding to the Array.prototype object), your new function will be available to all arrays you subsequently create. (I should make a quick qualification, however: You're not modifying the JavaScript runtime itself; if you're writing code for a web page, you need to include the code for your new function in the page's JavaScript code so it's available every time the page loads.)
Here's a function that does the job:
Array.prototype.indexOf = function (element) {
for (var i = 0; i < this.length; i++) {
if (this[i] == element) {
return i;
}
}
return -1;
};
Done. Now your arrays have a function called indexOf, which determines whether the array contains an element, and if so, what the index is of the element; and if the element isn't present, the function returns -1.
Try it:
alert(myarray.indexOf(10))
(Notice something cool, if you did this code in the same order I'm presenting it: Even though you added the indexOf function to the Array.prototype object after you created your array, the function is, nevertheless, now available to your array!)
Where to go next
If you look through the official specification, you'll see that the object mechanism goes well beyond these four short articles I've written. JavaScript includes strings as well as an underlying built-in String object that provides a prototype for all string objects. There's also a Boolean object, and a Number object, among others. At this point, I strongly encourage you to explore the specification. And remember, these descriptions apply to the single built-in object by the name (such as the Number object and the Boolean object). But each has a prototype object, too, which provides a basis for your own number and boolean objects.
Finally, remember as I mentioned earlier that if you extend these built-in single objects yourself by adding new functions, the code declaring such functions must be present in each of your JavaScript programs, as you're not extending the engine itself. Typically this will mean putting your extension code in a .js file (or several .js files) and then including it in your web pages, like so:
<script type="text/javascript" src="myextensions.js"></script>
Where myextensions.js contains your extensions. Then any code that follows can make use of the extensions.
Good luck, and have fun. And as usual, let me know if there are other topics you'd like to see in the series.
|
![]() |
|


