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

592APPENDIX B

JavaScript for object-oriented programmers

B.2 Objects in JavaScript

JavaScript doesn’t require the use of objects or even functions. It is possible to write a JavaScript program as a single stream of text that is executed directly as it is read by the interpreter. As a program gets bigger, though, functions and objects become a tremendously useful way of organizing your code, and we recommend you use both.

The simplest way to create a new JavaScript object is to invoke the built-in constructor for the Object class:

var myObject=new Object();

We’ll look at other approaches, and what the new keyword really does, in section B.2.2. Our object myObject is initially “empty,” that is, it has no properties or methods. Adding them in is quite simple, so let’s see how to do it now.

B.2.1 Building ad hoc objects

As already noted, the JavaScript object is essentially just an associative array, with fields and methods keyed by name. A C-like syntax is slapped on top to make it look familiar to C-family programmers, but the underlying implementation can be exploited in other ways, too. We can build up complex objects line by line, adding new variables and functions as we think of them.

There are two ways of building up objects in this ad hoc fashion. The first of these is to simply use JavaScript to create the object. The second is to use a special notation known as JSON. Let’s start with the plain old JavaScript technique.

Using JavaScript statements

In the middle of a complicated piece of code, we may want to assign a value to some object’s property. JavaScript object properties are read/write and can be assigned by the = operator. Let’s add a property to our simple object:

myObject.shoeSize="12";

In a structured OO language, we would need to define a class that declared a property shoeSize or else suffer a compiler error. Not so with JavaScript. In fact, just to emphasize the array-like nature, we can also reference properties using array syntax:

myObject['shoeSize']="12";

This notation is clumsy for ordinary use but has the advantage that the array index is a JavaScript expression, offering a form of runtime reflection, which we’ll return to in section B.2.4.

Objects in JavaScript

593

 

 

We can also add a new function to our object dynamically:

myObject.speakYourShoeSize=function(){ alert("shoe size : "+this.shoeSize);

}

Or borrow a predefined function:

function sayHello(){

alert('hello, my shoeSize is '+this.shoeSize);

}

...

myObject.sayHello=sayHello;

Note that in assigning the predefined function, we omit the parentheses. If we were to write

myObject.sayHello=sayHello();

then we would execute the sayHello function and assign the return value, in this case null, to the sayHello property of myObject.

We can attach objects to other objects in order to build up complex data models and so on:

var myLibrary=new Object(); myLibrary.books=new Array(); myLibrary.books[0]=new Object();

myLibrary.books[0].title="Turnip Cultivation through the Ages"; myLibrary.books[0].authors=new Array();

var jim=new Object(); jim.name="Jim Brown"; jim.age=9;

myLibrary.books[0].authors[0]=jim;

This can quickly become tedious (often the case where turnips are involved, I’m afraid), and JavaScript offers a compact notation that we can use to assemble object graphs more quickly, known as JSON. Let’s have a look at it now.

Using JSON

The JavaScript Object Notation (JSON) is a core feature of the language. It provides a concise mechanism for creating arrays and object graphs. In order to understand JSON, we need to know how JavaScript arrays work, so let’s cover the basics of them first.

JavaScript has a built-in Array class that can be instantiated using the new keyword:

myLibrary.books=new Array();

594APPENDIX B

JavaScript for object-oriented programmers

Arrays can have values assigned to them by number, much like a conventional C or Java array:

myLibrary.books[4]=somePredefinedBook;

Or they can be associated with a key value, like a Java Map or Python Dictionary, or, indeed, any JavaScript Object:

myLibrary.books["BestSeller"]=somePredefinedBook;

This syntax is good for fine-tuning, but building a large array or object in the first place can be tedious. The shorthand for creating a numerically indexed array is to use square braces, with the entries being written as a comma-separated list of values, thus:

myLibrary.books=[predefinedBook1,predefinedBook2,predefinedBook3];

And to build a JavaScript Object, we use curly braces, with each value written as a key:value pair:

myLibrary.books={

bestSeller

:

predefinedBook1,

cookbook

:

predefinedBook2,

spaceFiller : predefinedBook3

};

In both notations, extra white space is ignored, allowing us to pretty-print for clarity. Keys can also have spaces in them, and can be quoted in the JSON notation, for example:

"Best Seller" : predefinedBook1,

We can nest JSON notations to create one-line definitions of complex object hierarchies (albeit rather a long line):

var myLibrary={

location : "my house",

keywords : [ "root vegetables", "turnip", "tedium" ], books: [

{

title : "Turnip Cultivation through the Ages", authors : [

{name: "Jim Brown", age: 9 },

{name: "Dick Turnip", age: 312 }

],

publicationDate : "long ago" },

{

title : "Turnip Cultivation through the Ages, vol. 2",

Objects in JavaScript

595

 

 

authors : [

{ name: "Jim Brown", age: 35 }

],

publicationDate : new Date(1605,11,05)

}

]

};

I have assigned three properties to the myLibrary object here: location is a simple string, keywords is a numerical list of strings, and books a numerically indexed list of objects, each with a title (a string), a publication date (a JavaScript Date object in one case and a string in the other), and a list of authors (an array). Each author is represented by a name and age parameter. JSON has provided us with a concise mechanism for creating this information in a single pass, something that would otherwise have taken many lines of code (and greater bandwidth).

Sharp-eyed readers will have noted that we populated the publication date for the second book using a JavaScript Date object. In assigning the value we can use any JavaScript code, in fact, even a function that we defined ourselves:

function gunpowderPlot(){ return new Date(1605,11,05);

}

var volNum=2;

var turnipVol2={

title : "Turnip Cultivation through the Ages, vol. " +volNum,

authors : [

{name: "Jim Brown", age: 35 } ],

publicationDate : gunpowderPlot()

}

]

};

Here the title of the book is calculated dynamically by an inline expression, and the publicationDate is set to the return value from a predefined function.

In the previous example, we defined a function gunpowderPlot() that was evaluated at the time the object was created. We can also define member functions for our JSON-invoked objects, which can be invoked later by the object:

var turnipVol2={

title : "Turnip Cultivation through the Ages, vol. "+volNum, authors : [

{name: "Jim Brown", age: 35 } ],

596APPENDIX B

JavaScript for object-oriented programmers

publicationDate : gunpowderPlot()

}

],

summarize:function(len){ if (!len){ len=7; }

var summary=this.title+" by " +this.authors[0].name

+" and his cronies is very boring. Z"; for (var i=0;i<len;i++){

summary+="z";

}

alert(summary);

}

};

...

turnipVol2.summarize(6);

The summarize() function has all the features of a standard JavaScript function, such as parameters and a context object identified by the keyword this. Indeed, once the object is created, it is just another JavaScript object, and we can mix and match the JavaScript and JSON notations as we please. We can use JavaScript to fine-tune an object declared in JSON:

var numbers={ one:1, two:2, three:3 }; numbers.five=5;

We initially define an object using JSON syntax and then add to it using plain JavaScript. Equally, we can extend our JavaScript-created objects using JSON:

var cookbook=new Object(); cookbook.pageCount=321; cookbook.author={

firstName: "Harry", secondName: "Christmas",

birthdate: new Date(1900,2,29), interests: ["cheese","whistling",

"history of lighthouse keeping"]

};

With the built-in JavaScript Object and Array classes and the JSON notation, we can build object hierarchies as complicated as we like, and we could get by with nothing else. JavaScript also offers a means for creating objects that provides a comforting resemblance to class definitions for OO programmers, so let’s look at this next and see what it can offer us.