Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ajax In Action (2006).pdf
Скачиваний:
63
Добавлен:
17.08.2013
Размер:
8.36 Mб
Скачать

Objects in JavaScript

597

 

 

B.2.2 Constructor functions, classes, and prototypes

In OO programming, we generally create objects by stating the class from which we want them to be instantiated. Both Java and JavaScript support the new keyword, allowing us to create instances of a predefined kind of object. Here the similarity between the two ends.

In Java, everything (bar a few primitives) is an object, ultimately descended from the java.lang.Object class. The Java virtual machine has a built-in understanding of classes, fields, and methods, and when we declare in Java

MyObject myObj=new MyObject(arg1,arg2);

we first declare the type of the variable and then instantiate it using the relevant constructor. The prerequisite for success is that the class MyObject has been declared and offers a suitable constructor.

JavaScript, too, has a concept of objects and classes but no built-in concept of inheritance. In fact, every JavaScript object is really an instance of the same base class, a class that is capable of binding member fields and functions to itself at runtime. So, it is possible to assign arbitrary properties to an object on the fly:

MyJavaScriptObject.completelyNewProperty="something";

This free-for-all can be organized into something more familiar to the poor OO developer by using a prototype, which defines properties and functions that will automatically be bound to an object when it is constructed using a particular function. It is possible to write object-based JavaScript without the use of prototypes, but they offer a degree of regularity and familiarity to OO developers that is highly desirable when coding complex rich-client applications.

In JavaScript, then, we can write something that looks similar to the Java declaration

var myObj=new MyObject();

but we do not define a class MyObject, but rather a function with the same name. Here is a simple constructor:

function MyObject(name,size){ this.name=name; this.size=size;

}

We can subsequently invoke it as follows:

var myObj=new MyObject("tiddles","7.5 meters"); alert("size of "+myObj.name+" is "+myObj.size);

598APPENDIX B

JavaScript for object-oriented programmers

Anything set as a property of this in the constructor is subsequently available as a member of the object. We might want to internalize the call to alert() as well, so that tiddles can take responsibility for telling us how big it is. One common idiom is to declare the function inside the constructor:

function MyObject(name,size){ this.name=name; this.size=size; this.tellSize=function(){

alert("size of "+this.name+" is "+this.size);

}

}

var myObj=new Object("tiddles","7.5 meters"); myObj.tellSize();

This works, but is less than ideal in two respects. First, for every instance of MyObject that we create, we create a new function. As responsible Ajax programmers, memory leaks are never far from our minds (see chapter 7), and if we plan on creating many such objects, we should certainly avoid this idiom. Second, we have accidentally created a closure here—in this case a fairly harmless one—but as soon as we involve DOM nodes in our constructor, we can expect more serious problems. We’ll look at closures in more detail later in this appendix. For now, let’s look at the safer alternative, which is something known as a prototype.

A prototype is a property of JavaScript objects, for which no real equivalent exists in OO languages. Functions and properties can be associated with a constructor’s prototype. The prototype and new keyword will then work together, and, when a function is invoked by new, all properties and methods of the prototype for the function are attached to the resulting object. That sounds a bit strange, but it’s simple enough in action:

function MyObject(name,size){ this.name=name; this.size=size;

}

MyObject.prototype.tellSize=function(){ alert("size of "+this.name+" is "+this.size);

}

var myObj=new MyObject("tiddles","7.5 meters"); myObj.tellSize();

First, we declare the constructor as before, and then we add functions to the prototype. When we create an instance of the object, the function is attached. The keyword this resolves to the object instance at runtime, and all is well.

Objects in JavaScript

599

 

 

Note the ordering of events here. We can refer to the prototype only after the constructor function is declared, and objects will inherit from the prototype only what has already been added to it before the constructor is invoked. The prototype can be altered between invocations to the constructor, and we can attach anything to the prototype, not just a function:

MyObject.prototype.color="red"; var obj1=new MyObject();

MyObject.prototype.color="blue";

MyObject.prototype.soundEffect="boOOOoing!!"; var obj2=new MyObject();

obj1 will be red, with no sound effect, and obj2 will be blue with an annoyingly cheerful sound effect! There is generally little value in altering prototypes on the fly in this way. It’s useful to know that such things can happen, but using the prototype to define class-like behavior for JavaScript objects is the safe and sure route.

Interestingly, the prototype of certain built-in classes (that is, those implemented by the browser and exposed through JavaScript, also known as host objects) can be extended, too. Let’s have a look at how that works now.

B.2.3 Extending built-in classes

JavaScript is designed to be embedded in programs that can expose their own native objects, typically written in C++ or Java, to the scripting environment. These objects are usually described as built-in or host objects, and they differ in some regards to the user-defined objects that we have discussed so far. Nonetheless, the prototype mechanism can work with built-in classes, too. Within the web browser, DOM nodes cannot be extended in the Internet Explorer browser, but other core classes work across all major browsers. Let’s take the Array class as an example and define a few useful helper functions:

Array.prototype.indexOf=function(obj){ var result=-1;

for (var i=0;i<this.length;i++){ if (this[i]==obj){

result=i;

break;

}

}

return result;

}

600APPENDIX B

JavaScript for object-oriented programmers

This provides an extra function to the Array object that returns the numerical index of an object in a given array, or -1 if the array doesn’t contain the object. We can build on this further, writing a convenience method to check whether an array contains an object:

Array.prototype.contains=function(obj){ return (this.indexOf(obj)>=0);

}

and then add another function for appending new members after optionally checking for duplicates:

Array.prototype.append=function(obj,nodup){ if (!(nodup && this.contains(obj))){

this[this.length]=obj;

}

}

Any Array objects created after the declaration of these functions, whether by the new operator or as part of a JSON expression, will be able to use these functions:

var numbers=[1,2,3,4,5];

var got8=numbers.contains(8); numbers.append("cheese",true);

As with the prototypes of user-defined objects, these can be manipulated in the midst of object creation, but I generally recommend that the prototype be modified once only at the outset of a program, to avoid unnecessary confusion, particularly if you’re working with a team of programmers.

Prototypes can offer us a lot, then, when developing client-side object models for our Ajax applications. A meticulous object modeler used to C++, Java, or C# may not only want to define various object types but to implement inheritance between types. JavaScript doesn’t offer this out of the box, but the prototype can come in useful here, too. Let’s find out how.

B.2.4 Inheritance of prototypes

Object orientation provides not only support for distinct object classes but also a structured hierarchy of inheritance between them. The classic example is the Shape object, which defines methods for computing perimeter and area, on top of which we build concrete implementations for rectangles, squares, triangles, and circles.

With inheritance comes the concept of scope. The scope of an object’s methods or properties determines who can use it—that is, whether it is public, private, or protected.