Main Page

Very late binding

You may recall from Chapter 2 that the
method normally outputs the source
code of the function. By overriding that method, you can supply a different string to return (in this case,
“Function code hidden”
). But what happened to the original function that
was point-
ing to? Well, it has gone on to the garbage collector because it was fully dereferenced. You have no way
to get that original function back, which is why it is always safer to store a pointer to the original method
that you are overriding, just in case you need it later. You may even want to call that original method
under certain circumstances in your new method:
Function.prototype.originalToString = Function.prototype.toString;
Function.prototype.toString = function () {
if (this.originalToString().length > 100) {
return “Function too long to display.”;
} else {
return this.originalToString();
In this code, the first line saves a reference to the current
method in a property called
. Then, the
method is overridden with a custom method. This new
method checks to see if the length of the function source code is longer greater than 100. If so, the
method returns a small error message stating that the function code is too long; otherwise, it returns
the source code by calling
Very late binding
Technically speaking, there is no such thing as very late binding. The term is used in this book to describe
a phenomenon in ECMAScript where it is possible to define a method for a type of object after the object
has already been instantiated. For example:
var o = new Object;
Object.prototype.sayHi = function () {
In most programming languages, you must define object methods well in advance of object instantia-
tion. Here, the
method is added to the
class after an instance has been created. Not
only is that unheard of in traditional languages, but the instance of
is then automatically
assigned the method and it can be used immediately (on the following line).
It is not recommended that you use very late binding because it can be difficult to
keep track of and document. However, you should understand that it is possible.
Object Basics
06_579088 ch03.qxd 3/28/05 11:36 AM Page 101

JavaScript EditorFree JavaScript Editor     Ajax Editor