﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-JAVA学习点点滴滴-随笔分类-JavaScript</title><link>http://www.blogjava.net/mkchen/category/19388.html</link><description>用开放的脑子去闯荡;用开阔的视野去拼搏;用平和的身心去磨练;用美好的理想去追求!</description><language>zh-cn</language><lastBuildDate>Fri, 02 Mar 2007 06:38:17 GMT</lastBuildDate><pubDate>Fri, 02 Mar 2007 06:38:17 GMT</pubDate><ttl>60</ttl><item><title>Object Hierarchy and Inheritance in JavaScript</title><link>http://www.blogjava.net/mkchen/archive/2007/01/21/95144.html</link><dc:creator>海思</dc:creator><author>海思</author><pubDate>Sun, 21 Jan 2007 08:19:00 GMT</pubDate><guid>http://www.blogjava.net/mkchen/archive/2007/01/21/95144.html</guid><wfw:comment>http://www.blogjava.net/mkchen/comments/95144.html</wfw:comment><comments>http://www.blogjava.net/mkchen/archive/2007/01/21/95144.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/mkchen/comments/commentRss/95144.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/mkchen/services/trackbacks/95144.html</trackback:ping><description><![CDATA[
		<center>
				<h2>
						<a name="1027581">Object Hierarchy and Inheritance in JavaScript</a>
				</h2>
		</center>
		<a name="1027676">JavaScript is an object-oriented language based on prototypes, rather than, as is common, being class-based. Because of this different basis, it can be less apparent how JavaScript allows you to create hierarchies of objects and to have inheritance of properties and their values. This paper attempts to clarify the situation. If you're interested in precise details of how this all works, you can read the ECMA-262 JavaScript language specification (as a <a href="http://developer.netscape.com/library/javascript/e262-pdf.pdf" target="_top">PDF file</a> or a <a href="http://developer.netscape.com/library/javascript/e262-doc.exe" target="_top">Microsoft Word self-extracting binary</a>). 
<p></p></a>
		<a name="1032424">This paper assumes that you're already somewhat familiar with JavaScript and that you have used JavaScript functions to create simple objects. For information on this subject, see <a href="http://developer.netscape.com/library/documentation/communicator/jsguide4/index.htm?content=model.htm" target="_top">Chapter 10, "Object Model,"</a> in the <em><a href="http://developer.netscape.com/library/documentation/communicator/jsguide4/index.htm" target="_top">JavaScript Guide</a></em>. 
<p></p></a>
		<a name="1041991">The sections in this paper are: 
<p></p></a>
		<ul>
				<a name="1041992">
						<li>
								<a href="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/index.htm#1030757">The Employee Example</a>
						</li>
				</a>
				<a name="1041997">
						<li>
								<a href="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/index.htm#1030750">Creating the Hierarchy</a>
						</li>
				</a>
				<a name="1042002">
						<li>
								<a href="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/index.htm#1035076">Object Properties</a>
						</li>
				</a>
				<a name="1042007">
						<li>
								<a href="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/index.htm#1044609">More Flexible Constructors</a>
						</li>
				</a>
				<a name="1042012">
						<li>
								<a href="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/index.htm#1040208">Property Inheritance Revisited</a>
						</li>
				</a>
		</ul>
		<a name="1030639">Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances. A <b>class</b> defines all of the properties (considering methods and fields in Java, or members in C++, to be properties) that characterize a certain set of objects. A class is an abstract thing, rather than any particular member of the set of objects it describes. For example, the <code>Employee</code> class could represent the set of all employees. An <b>instance</b>, on the other hand, is the instantiation of a class; that is, one of its members. For example, <code>Victoria</code> could be an instance of the <code>Employee</code> class, representing a particular individual as an employee. An instance has exactly the properties of its parent class (no more, no less). 
<p></p></a>
		<a name="1044714">A prototype-based language, such as JavaScript, does not make this distinction: it simply has objects. A prototype-based language has the notion of a <b>prototypical object</b>, an object used as a template from which to get the initial properties for a new object. Any object can specify its own properties, either when you create it or even at runtime. In addition, any object can be associated as the <b>prototype</b> for another object, allowing the second object to share the first object's properties. 
<p></p></a>
		<a name="1031000">In class-based languages, you define a class in a separate <b>class definition</b>. In that definition you can specify special methods, called <b>constructors</b>, to use to create instances of the class. A constructor method can specify initial values for the instance's properties and perform other processing appropriate at creation time. You use the <b>new</b> operator in association with the constructor method to create class instances. 
<p></p></a>
		<a name="1031044">JavaScript follows a similar model, but does not have a class definition separate from the constructor. Instead, you define a constructor function to create objects with a particular initial set of properties and values. Any JavaScript function can be used as a constructor. You use the <b>new</b> operator with a constructor function to create a new object. 
<p></p></a>
		<a name="1030424">In a class-based language, you create a hierarchy of classes through the class definitions. In a class definition, you can specify that the new class is a <b>subclass</b> of an already existing class. The subclass inherits all the properties of the superclass and additionally can add new properties or modify the inherited ones. For example, assume the <code>Employee</code> class includes only <code>name</code> and <code>dept</code> properties and <code>Manager</code> is a subclass of <code>Employee</code> that adds the <code>reports</code> property. In this case, an instance of the <code>Manager</code> class would have all three properties: <code>name</code>, <code>dept</code>, and <code>reports</code>. 
<p></p></a>
		<a name="1031408">JavaScript implements inheritance by allowing you to associate a prototypical object with any constructor function. So, you can create exactly the <code>Employee</code>-<code>Manager</code> example, but you use slightly different terminology. First you define the <code>Employee</code> constructor function, specifying the <code>name</code> and <code>dept</code> properties. Next, you define the <code>Manager</code> constructor function, specifying the <code>reports</code> property. Finally, you assign a new <code>Employee</code> object as the <code>prototype</code> for the <code>Manager</code> constructor function. Then, when you create a new <code>Manager</code>, it inherits the <code>name</code> and <code>dept</code> properties from the <code>Employee</code> object. 
<p></p></a>
		<a name="1030703">In class-based languages, you typically create a class at compile time and then you instantiate instances of the class either at compile time or at runtime. You cannot change the number or the type of properties of a class after you define the class. In JavaScript, however, at runtime you can add or remove properties from any object. If you add a property to an object that is used as the prototype for a set of objects, the objects for which it is the prototype also get the new property. 
<p></p></a>
		<a name="1031978">
				<a href="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/index.htm#1031117">Table 1</a> gives a short summary of some of these differences. The rest of this paper describes the details of using JavaScript constructors and prototypes to create an object hierarchy and compares this to how you would do it in Java. 
<p><b><a name="1031117">Table 1 Comparison of class-based (Java) and prototype-based (JavaScript) object systems</a></b></p><table border="2"><tbody><tr><th valign="baseline" align="left"><b><a name="1031121"><b>Class-based (Java) </b></a></b></th><th valign="baseline" align="left"><b><a name="1031123"><b>Prototype-based (JavaScript) </b></a></b></th></tr><tr><td valign="baseline" align="left"><a name="1031125">Class and instance are distinct entities.</a><p></p></td><td valign="baseline" align="left"><a name="1031127">All objects are instances.</a><p></p></td></tr><tr><td valign="baseline" align="left"><a name="1031142">Define a class with a class definition; instantiate a class with constructor methods.</a><p></p></td><td valign="baseline" align="left"><a name="1031144">Define and create a set of objects with constructor functions.</a><p></p></td></tr><tr><td valign="baseline" align="left"><a name="1031159">Create a single object with the <code>new</code> operator.</a><p></p></td><td valign="baseline" align="left"><a name="1031161">Same.</a><p></p></td></tr><tr><td valign="baseline" align="left"><a name="1031168">Construct an object hierarchy by using class definitions to define subclasses of existing classes.</a><p></p></td><td valign="baseline" align="left"><a name="1031170">Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.</a><p></p></td></tr><tr><td valign="baseline" align="left"><a name="1031248">Inherit properties by following the class chain.</a><p></p></td><td valign="baseline" align="left"><a name="1031250">Inherit properties by following the prototype chain.</a><p></p></td></tr><tr><td valign="baseline" align="left"><a name="1031331">Class definition specifies <i>all</i> properties of all instances of a class. No way to add properties dynamically at runtime.</a><p></p></td><td valign="baseline" align="left"><a name="1031333">Constructor function or prototype specifies an <i>initial set</i> of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.</a><p></p></td></tr></tbody></table><table><tbody><tr><td></td></tr></tbody></table><p></p></a>
		<a name="The Employee Example">
		</a>
		<a name="1030757">
				<h2>The Employee Example</h2>
		</a>
		<a name="1032252">The rest of this paper works with the simple employee hierarchy shown in <a href="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/index.htm#1032301">Figure 1</a>. 
<p></p></a>
		<a name="1032301">
				<b>Figure 1    A simple object hierarchy 
<p><img src="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/hier01.gif" /></p></b>
				<p>
				</p>
		</a>
		<p>
				<a name="1032257">
						<li>
								<code>Employee</code> has the properties <code>name</code> (whose value defaults to the empty string) and <code>dept</code> (whose value defaults to <code>"general"</code>). </li>
				</a>
		</p>
		<p>
				<a name="1032258">
				</a>
		</p>
		<li>
				<code>Manager</code> is based on <code>Employee</code>. It adds the <code>reports</code> property (whose value defaults to an empty array, intended to have an array of <code>Employee</code> objects as its value). <p><a name="1032180"></a></p></li>
		<li>
				<code>WorkerBee</code> is also based on <code>Employee</code>. It adds the <code>projects</code> property (whose value defaults to an empty array, intended to have an array of strings as its value). <p><a name="1032195"></a></p></li>
		<li>
				<code>SalesPerson</code> is based on <code>WorkerBee</code>. It adds the <code>quota</code> property (whose value defaults to 100). It also overrides the <code>dept</code> property with the value <code>"sales"</code>, indicating that all salespersons are in the same department. <p><a name="1032216"></a></p></li>
		<li>
				<code>Engineer</code> is based on <code>WorkerBee</code>. It adds the <code>machine</code> property (whose value defaults to the empty string) and also overrides the <code>dept</code> property with the value <code>"engineering"</code>. <a name="Creating the Hierarchy"></a><a name="1030750"><h2>Creating the Hierarchy</h2></a><a name="1034964">There are several ways you can define appropriate constructor functions to implement the Employee hierarchy. How you choose to define them depends largely on what you want to be able to do in your application. We'll get into all that later. 
<p></p></a><a name="1035051">For now, let's use very simple (and comparatively inflexible) definitions just to see how we get the inheritance to work. In these definitions, you can't specify any property values when you create an object. The newly-created object simply gets the default values, which you can change at a later time. <a href="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/index.htm#1035015">Figure 2</a> illustrates the hierarchy with these simple definitions. 
<p></p></a><a name="1046083">In a real application, you would probably define constructors that allow you to provide property values at object creation time. Options for doing so are described later in <a href="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/index.htm#1044609">"More Flexible Constructors"</a>. For now, these simple definitions let us look at how the inheritance occurs. 
<p></p></a><a name="1035015"><b>Figure 2    What the definitions look like 
<p><img src="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/hier02.gif" /></p></b><p></p></a><a name="1042271">The simple Java and JavaScript <code>Employee</code> definitions below are similar. The only difference is that you need to specify the type for each property in Java but not in JavaScript and you need to create an explicit constructor method for the Java class. 
<p><b></b></p><table border="2"><tbody><tr><th valign="baseline" align="left"><b><a name="1044938"><b>JavaScript </b></a></b></th><th valign="baseline" align="left"><b><a name="1042338"><b>Java </b></a></b></th></tr><tr><td valign="baseline" align="left"><a name="1042340"><pre>function Employee () {<br />    this.name = "";<br />    this.dept = "general";<br />}</pre></a></td><td valign="baseline" align="left"><a name="1042342"><pre>public class Employee {<br />   public String name;<br />   public String dept;<br />   public Employee () {<br />      this.name = "";<br />      this.dept = "general";<br />   }<br />}</pre></a></td></tr></tbody></table><table><tbody><tr><td></td></tr></tbody></table><p></p></a><a name="1042297">The <code>Manager</code> and WorkerBee definitions show the difference in how you specify the next object higher in the inheritance chain. In JavaScript, you add a prototypical instance as the value of the <code>prototype</code> property of the constructor function. You can do so at any time after you define the constructor. In Java, you specify the superclass within the class definition. You cannot change the superclass outside the class definition. 
<p><b></b></p><table border="2"><tbody><tr><th valign="baseline" align="left"><b><a name="1042370"><b>JavaScript </b></a></b></th><th valign="baseline" align="left"><b><a name="1042372"><b>Java </b></a></b></th></tr><tr><td valign="baseline" align="left"><a name="1042378"><pre>function Manager () {<br />    this.reports = [];<br />}<br />Manager.prototype = new Employee;</pre></a><a name="1042382"><pre>function WorkerBee () {<br />    this.projects = [];<br />}<br />WorkerBee.prototype = new Employee;</pre></a></td><td valign="baseline" align="left"><a name="1042380"><pre>public class Manager extends Employee {<br />   public Employee[] reports;<br />   public Manager () {<br />      this.reports = new Employee[0];<br />   }<br />}</pre></a><a name="1042384"><pre>public class WorkerBee extends Employee {<br />   public String[] projects;<br />   public WorkerBee () {<br />      this.projects = new String[0];<br />   }<br />}</pre></a></td></tr></tbody></table><table><tbody><tr><td></td></tr></tbody></table><p></p></a><a name="1042306">The <code>Engineer</code> and <code>SalesPerson</code> definitions create objects that descend from <code>WorkerBee</code> and hence from <code>Employee</code>. An object of these types has properties of all the objects above it in the chain. In addition, these definitions override the inherited value of the <code>dept</code> property with new values specific to these objects. 
<p><b></b></p><table border="2"><tbody><tr><th valign="baseline" align="left"><b><a name="1042437"><b>JavaScript </b></a></b></th><th valign="baseline" align="left"><b><a name="1042439"><b>Java </b></a></b></th></tr><tr><td valign="baseline" align="left"><a name="1042766"><pre>function SalesPerson () {<br />   this.dept = "sales";<br />   this.quota = 100;<br />}<br />SalesPerson.prototype = new WorkerBee;</pre></a><a name="1042453"><pre>function Engineer () {<br />   this.dept = "engineering";<br />   this.machine = "";<br />}<br />Engineer.prototype = new WorkerBee;</pre></a></td><td valign="baseline" align="left"><a name="1042768"><pre>public class SalesPerson extends WorkerBee {<br />   public double quota;<br />   public SalesPerson () {<br />      this.dept = "sales";<br />      this.quota = 100.0;<br />   }<br />}</pre></a><a name="1042455"><pre>public class Engineer extends WorkerBee {<br />   public String machine;<br />   public Engineer () {<br />      this.dept = "engineering";<br />      this.machine = "";<br />   }<br />}</pre></a></td></tr></tbody></table><table><tbody><tr><td></td></tr></tbody></table><p></p></a><a name="1033212">Using these definitions, you can create instances of these objects that get the default values for their properties. <a href="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/index.htm#1035230">Figure 3</a> illustrates using these JavaScript definitions to create new objects and shows the property values for the new objects. 
<p></p></a><blockquote><b>NOTE: </b><a name="1036464">As described earlier, the term <b>instance</b> has a specific technical meaning in class-based languages. In these languages, an instance is an individual member of a class and is fundamentally different from a class. In JavaScript, "instance" does not have this technical meaning because JavaScript does not have this difference between classes and instances. However, in talking about JavaScript, "instance" can be used informally to mean an object created using a particular constructor function. So, in this example, you could informally say that <code>jane</code> is an instance of <code>Engineer</code>. Similarly, although the terms <b>parent</b>, <b>child</b>, <b>ancestor</b>, and <b>descendant</b> do not have formal meanings in JavaScript, we can use them informally to refer to objects higher or lower in the prototype chain. </a></blockquote><a name="1035230"><b>Figure 3    Creating objects with the simple definitions 
<p><img src="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/hier03.gif" /></p></b><p></p></a><a name="Object Properties"></a><a name="1035076"><h2>Object Properties</h2></a><a name="1044591">This section discusses how objects inherit properties from other objects in the prototype chain and what happens when you add a property at runtime. 
<p></p></a><a name="Head2;"></a><a name="1042848"><h3>Inheriting Properties</h3></a><a name="1037638">Assume you create the <code>mark</code> object as a <code>WorkerBee</code> as shown in <a href="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/index.htm#1035230">Figure 3</a> with this statement: 
<p></p></a><a name="1037887"><pre>mark = new WorkerBee;</pre></a><a name="1037915">When JavaScript sees the <code>new</code> operator, it creates a new generic object and passes this new object as the value of the <code>this</code> keyword to the <code>WorkerBee</code> constructor function. The constructor function explicitly sets the value of the <code>projects</code> property. It also sets the value of the internal <code>__proto__</code> property to the value of <code>WorkerBee.prototype</code>. (That property name has 2 underscore characters at the front and 2 at the end.) The <code>__proto__</code> property determines the prototype chain used to return property values. Once these properties are set, JavaScript returns the new object and the assignment statement sets the variable <code>mark</code> to that object. 
<p></p></a><a name="1038044">This process doesn't explicitly put values in the <code>mark</code> object (<b>local</b> values) for the properties <code>mark</code> inherits from the prototype chain. When you ask for the value of a property, JavaScript first checks to see if the value exists in that object. If it does, that value is returned. If the value isn't there locally, JavaScript checks the prototype chain (using the <code>__proto__</code> property). If an object in the prototype chain has a value for the property, that value is returned. If no such property is found, JavaScript says the object doesn't have the property. In this way, the <code>mark</code> object has the following properties and values: 
<p></p></a><a name="1037606"><pre>mark.name = "";<br />mark.dept = "general";<br />mark.projects = [];</pre></a><a name="1046148">The <code>mark</code> object inherits values for the <code>name</code> and <code>dept</code> properties from the prototypical object in <code>mark.__proto__</code>. It is assigned a local value for the <code>projects</code> property by the <code>WorkerBee</code> constructor. Simply put, this gives you inheritance of properties and their values in JavaScript. Some subtleties of this process are discussed in <a href="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/index.htm#1040208">"Property Inheritance Revisited"</a>. 
<p></p></a><a name="1037968">Because these constructors don't let you supply instance-specific values, this information is generic. The property values are the default ones shared by all new objects created from <code>WorkerBee</code>. You can, of course, change the values of any of these properties. So, you could give specific information for <code>mark</code> as shown here: 
<p></p></a><a name="1037728"><pre>mark.name = "Doe, Mark";<br />mark.dept = "admin";<br />mark.projects = ["navigator"];</pre></a><a name="Head2;"></a><a name="1042890"><h3>Adding Properties</h3></a><a name="1042885">In JavaScript at runtime you can add properties to any object. You are not constrained to use only the properties provided by the constructor function. To add a property that is specific to a single object, you simply assign a value to the object, as in: 
<p></p></a><a name="1037779"><pre>mark.bonus = 3000;</pre></a><a name="1037547">Now, the <code>mark</code> object has a <code>bonus</code> property, but no other <code>WorkerBee</code> has this property. 
<p></p></a><a name="1037800">If you add a new property to an object that is being used as the prototype for a constructor function, you add that property to all objects that inherit properties from the prototype. For example, you can add a <code>specialty</code> property to all employees with the following statement: 
<p></p></a><a name="1037805"><pre>Employee.prototype.specialty = "none";</pre></a><a name="1037810">As soon as JavaScript executes this statement, the <code>mark</code> object also has the <code>specialty</code> property with the value of <code>"none"</code>. <a href="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/index.htm#1037175">Figure 4</a> shows the effect of adding this property to the <code>Employee</code> prototype and then overriding it for the <code>Engineer</code> prototype. 
<p></p></a><a name="1037175"><b>Figure 4    Adding properties 
<p><img src="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/hier04.gif" /></p></b><p></p></a><a name="More Flexible Constructors"></a><a name="1044609"><h2>More Flexible Constructors</h2></a><a name="1041901">The constructor functions used so far do not let you specify property values when you create an instance. As with Java, you can provide arguments to constructors to initialize property values for instances. <a href="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/index.htm#1041961">Figure 5</a> shows one way to do this. 
<p></p></a><a name="1041961"><b>Figure 5    Specifying properties in a constructor, take 1 
<p><img src="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/hier05.gif" /></p></b><p></p></a><a name="1046365">Here are the Java and JavaScript definitions for these objects. 
<p><b></b></p><table border="2"><tbody><tr><th valign="baseline" align="left"><b><a name="1041592"><b>JavaScript </b></a></b></th><th valign="baseline" align="left"><b><a name="1041594"><b>Java </b></a></b></th></tr><tr><td valign="baseline" align="left"><a name="1041596"><pre>function Employee (name, dept) {<br />    this.name = name || "";<br />    this.dept = dept || "general";<br />}</pre></a></td><td valign="baseline" align="left"><a name="1043223"><pre>public class Employee {<br />   public String name;<br />   public String dept;<br />   public Employee () {<br />      this("", "general");<br />   }<br />   public Employee (name) {<br />      this(name, "general");<br />   }<br />   public Employee (name, dept) {<br />      this.name = name;<br />      this.dept = dept;<br />   }<br />}</pre></a></td></tr><tr><td valign="baseline" align="left"><a name="1043103"><pre>function WorkerBee (projs) {<br />    this.projects = projs || [];<br />}<br />WorkerBee.prototype = new Employee;</pre></a></td><td valign="baseline" align="left"><a name="1045331"><pre>public class WorkerBee extends Employee {<br />   public String[] projects;<br />   public WorkerBee () {<br />      this(new String[0]);<br />   }<br />   public WorkerBee (String[] projs) {<br />      this.projects = projs;<br />   }<br />}</pre></a></td></tr><tr><td valign="baseline" align="left"><a name="1043124"><pre>function Engineer (mach) {<br />   this.dept = "engineering";<br />   this.machine = mach || "";<br />}<br />Engineer.prototype = new WorkerBee;</pre></a></td><td valign="baseline" align="left"><a name="1043338"><pre>public class Engineer extends WorkerBee {<br />   public String machine;<br />   public WorkerBee () {<br />      this.dept = "engineering";<br />      this.machine = "";<br />   }<br />   public WorkerBee (mach) {<br />      this.dept = "engineering";<br />      this.machine = mach;<br />   }<br />}</pre></a></td></tr></tbody></table><table><tbody><tr><td></td></tr></tbody></table><p></p></a><a name="1041608">These JavaScript definitions use a special idiom for setting default values: 
<p></p></a><a name="1046531"><pre>this.name = name || "";</pre></a><a name="1046524">The JavaScript logical OR operator (<code>||</code>) evaluates its first argument. If that argument is converts to true, the operator returns it. Otherwise, the operator returns the value of the second argument. Therefore, this line of code tests to see if <code>name</code> has a useful value for the <code>name</code> property. If it does, it sets <code>this.name</code> to that value. Otherwise, it sets <code>this.name</code> to the empty string. This paper uses this idiom for brevity; however, it can be puzzling at first glance. 
<p></p></a><a name="1046540">With these definitions, when you create an instance of an object, you can specify values for the locally defined properties. As shown in <a href="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/index.htm#1041961">Figure 5</a>, you can use this statement to create a new <code>Engineer</code>: 
<p></p></a><a name="1039055"><pre>jane = new Engineer("belau");</pre></a><a name="1039064">Jane's properties are now: 
<p></p></a><a name="1039078"><pre>jane.name == "";<br />jane.dept == "general";<br />jane.projects == [];<br />jane.machine == "belau"</pre></a><a name="1039079">Notice that with these definitions, you cannot specify an initial value for an inherited property such as <code>name</code>. If you want to specify an initial value for inherited properties in JavaScript, you need to add more code to the constructor function. 
<p></p></a><a name="1039083">So far, the constructor function has created a generic object and then specified local properties and values for the new object. You can have the constructor add more properties by directly calling the constructor function for an object higher in the prototype chain. <a href="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/index.htm#1039186">Figure 6</a> shows these new definitions. 
<p></p></a><a name="1039186"><b>Figure 6    Specifying properties in a constructor, take 2 
<p><img src="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/hier06.gif" /></p></b><p></p></a><a name="1041693">Let's look at one of these definitions in detail. Here's the new definition for the <code>Engineer</code> constructor: 
<p></p></a><a name="1039389"><pre>function Engineer (name, projs, mach) {<br />    this.base = WorkerBee;<br />    this.base(name, "engineering", projs);<br />    this.projects = mach || "";<br />}</pre></a><a name="1039407">Assume we create a new <code>Engineer</code> object as follows: 
<p></p></a><a name="1039480"><pre>jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");</pre></a><a name="1039489">JavaScript follows these steps: 
<p></p></a><a name="1039507"><blockquote>1.   First, the <code>new</code> operator creates a generic object and sets its <code>__proto__</code> property to <code>Engineer.prototype</code>.</blockquote></a><a name="1046227"><blockquote>2.   The <code>new</code> operator then passes the new object to the <code>Engineer</code> constructor as the value of the <code>this</code> keyword.</blockquote></a><a name="1039547"><blockquote>3.   Next, the constructor creates a new property called <code>base</code> for that object and assigns the value of the <code>WorkerBee</code> constructor to the <code>base</code> property. This makes the <code>WorkerBee</code> constructor a method of the <code>Engineer</code> object.</blockquote></a><blockquote><b>NOTE: </b><a name="1039614">The name of the <code>base</code> property is not special. You can use any legal property name; <code>base</code> is simply evocative of its purpose. </a></blockquote><a name="1039548"><blockquote>4.   Next, the constructor calls the <code>base</code> method, passing as its arguments two of the arguments passed to the constructor (<code>"Doe, Jane"</code> and <code>["navigator", "javascript"]</code>) and also the string <code>"engineering"</code>. Explicitly using <code>"engineering"</code> in the constructor indicates that all <code>Engineer</code> objects have the same value for the inherited <code>dept</code> property and this value overrides the value inherited from <code>Employee</code>.</blockquote></a><a name="1043716"><blockquote>5.   Because <code>base</code> is a method of <code>Engineer</code>, within the call to <code>base</code>, JavaScript binds the <code>this</code> keyword to the object created in step 1. Thus, the <code>WorkerBee</code> function in turn passes the <code>"Doe, Jane"</code> and <code>["navigator", "javascript"]</code> arguments to the <code>Employee</code> constructor function. Upon return from the <code>Employee</code> constructor function, the <code>WorkerBee</code> function uses the remaining argument to set the <code>projects</code> property.</blockquote></a><a name="1039569"><blockquote>6.   Upon return from the <code>base</code> method, the <code>Engineer</code> constructor initializes the object's <code>machine</code> property to <code>"belau"</code>.</blockquote></a><a name="1039581"><blockquote>7.   Upon return from the constructor, JavaScript assigns the new object to the <code>jane</code> variable.</blockquote></a><a name="1043735">You might think that, having called the <code>WorkerBee</code> constructor from inside the <code>Engineer</code> constructor, you've set up inheritance appropriately for <code>Engineer</code> objects. This is not the case. Calling the <code>WorkerBee</code> constructor ensures that an <code>Engineer</code> object starts out with the properties specified in all constructor functions that are called. However, if you later add properties to the <code>Employee</code> or <code>WorkerBee</code> prototypes, those properties are not inherited by the <code>Engineer</code> object. For example, assume you have these statements: 
<p></p></a><a name="1043743"><pre>function Engineer (name, projs, mach) {<br />    this.base = WorkerBee;<br />    this.base(name, "engineering", projs);<br />    this.projects = mach || "";<br />}<br />jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");<br />Employee.prototype.specialty = "none";</pre></a><a name="1039690">The <code>jane</code> object does not inherit the <code>specialty</code> property. You still need to explicitly set up the prototype to ensure dynamic inheritance. Assume instead you have these statements: 
<p></p></a><a name="1043797"><pre>function Engineer (name, projs, mach) {<br />    this.base = WorkerBee;<br />    this.base(name, "engineering", projs);<br />    this.projects = mach || "";<br />}<br /><b>Engineer.prototype = new WorkerBee;<br /></b>jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");<br />Employee.prototype.specialty = "none";</pre></a><a name="1039736">Now the value of the <code>jane</code> object's <code>specialty</code> property is <code>"none"</code>. 
<p></p></a><a name="Property Inheritance Revisited"></a><a name="1040208"><h2>Property Inheritance Revisited</h2></a><a name="1040213">The preceding sections have described how constructors and prototypes provide hierarchies and inheritance in JavaScript. As with all languages, there are some subtleties that were not necessarily apparent in these earlier discussions. This section discusses some of those subtleties. 
<p></p></a><a name="Head2;"></a><a name="1039092"><h3>Local versus Inherited Values</h3></a><a name="1039778">Let's revisit property inheritance briefly. As discussed earlier, when you access an object property, JavaScript performs these steps: 
<p></p></a><ol><p><a name="1039805"><li>Check to see if the value exists locally. If it does, return that value. </li></a></p><p><a name="1039812"></a></p><li>If there isn't a local value, check the prototype chain (using the <code>__proto__</code> property). <p><a name="1039824"></a></p></li><li>If an object in the prototype chain has a value for the specified property, return that value. <p><a name="1039835"></a></p></li><li>If no such property is found, the object does not have the property. </li></ol><a name="1039784">The outcome of this simple set of steps depends on how you've defined things along the way. In our original example, we had these definitions: 
<p></p></a><a name="1039845"><pre>function Employee () {<br />    this.name = "";<br />    this.dept = "general";<br />}</pre></a><a name="1039850"><pre>function WorkerBee () {<br />    this.projects = [];<br />}<br />WorkerBee.prototype = new Employee;</pre></a><a name="1039842">With these definitions, assume you create <code>amy</code> as an instance of <code>WorkerBee</code> with this statement: 
<p></p></a><a name="1043601"><pre>amy = new WorkerBee;</pre></a><a name="1043596">The <code>amy</code> object has one local property, <code>projects</code>. The values for the <code>name</code> and <code>dept</code> properties are not local to <code>amy</code> and so are gotten from the <code>amy</code> object's <code>__proto__</code> property. Thus, <code>amy</code> has these property values: 
<p></p></a><a name="1040019"><pre>amy.name == "";<br />amy.dept = "general";<br />amy.projects == [];</pre></a><a name="1040018">Now assume you change the value of the <code>name</code> property in the prototype associated with <code>Employee</code>: 
<p></p></a><a name="1040014"><pre>Employee.prototype.name = "Unknown"</pre></a><a name="1040013">At first glance, you might expect that new value to propagate down to all the instances of <code>Employee</code>. However, it does not. 
<p></p></a><a name="1043836">When you create <i>any</i> instance of the <code>Employee</code> object, that instance gets a local value for the <code>name</code> property (the empty string). This means that when you set the <code>WorkerBee</code> prototype by creating a new <code>Employee</code> object, <code>WorkerBee.prototype</code> has a local value for the <code>name</code> property. Therefore, when JavaScript looks up the <code>name</code> property of the <code>amy</code> object (an instance of <code>WorkerBee</code>), JavaScript finds the local value for that property in <code>WorkerBee.prototype</code>. It therefore does not look farther up the chain to <code>Employee.prototype</code>. 
<p></p></a><a name="1040130">If you want to change the value of an object property at runtime and have the new value be inherited by all descendants of the object, you cannot define the property in the object's constructor function. Instead, you add it to the constructor's associated prototype. For example, assume you change the code above to the following: 
<p></p></a><a name="1040189"><pre>function Employee () {<br />   this.dept = "general";<br />}<br />Employee.prototype.name = "";</pre></a><a name="1040190"><pre>function WorkerBee () {<br />    this.projects = [];<br />}<br />WorkerBee.prototype = new Employee;</pre></a><a name="1040191"><pre>amy = new WorkerBee;</pre></a><a name="1040207"><pre>Employee.prototype.name = "Unknown";</pre></a><a name="1040183">In this case, the <code>name</code> property of <code>amy</code> becomes <code>"</code>Unknown<code>"</code>. 
<p></p></a><a name="1047098">As these examples show, if you want to have default values for object properties and you want to be able to change the default values at runtime, you should set the properties in the constructor's prototype, not in the constructor function itself. 
<p></p></a><a name="Head2;"></a><a name="1039116"><h3>Determining Instance Relationships</h3></a><a name="1043907">You may want to know what objects are in the prototype chain for an object, so that you can tell from what objects this object inherits properties. In a class-based language, you might have an <code>instanceof</code> operator for this purpose. JavaScript does not provide <code>instanceof</code>, but you can write such a function yourself. 
<p></p></a><a name="1044344">As discussed in <a href="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/index.htm#1042848">"Inheriting Properties"</a>, when you use the <code>new</code> operator with a constructor function to create a new object, JavaScript sets the <code>__proto__</code> property of the new object to the value of the <code>prototype</code> property of the constructor function. You can use this to test the prototype chain. 
<p></p></a><a name="1044353">For example, assume you have the same set of definitions we've been using, with the prototypes set appropriately. Create an <code>__proto__</code> object as follows: 
<p></p></a><a name="1044359"><pre>chris = new Engineer("Pigman, Chris", ["jsd"], "fiji");</pre></a><a name="1040250">With this object, the following statements are all true: 
<p></p></a><a name="1044375"><pre>chris.__proto__ == Engineer.prototype;<br />chris.__proto__.__proto__ == WorkerBee.prototype;<br />chris.__proto__.__proto__.__proto__ == Employee.prototype;<br />chris.__proto__.__proto__.__proto__.__proto__ == Object.prototype;<br />chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null;</pre></a><a name="1044416">Given this, you could write an <code>instanceOf</code> function as follows: 
<p></p></a><a name="1045649"><pre>function instanceOf(object, constructor) { <br />   while (object != null) { <br />      if (object == constructor.prototype) <br />         return true; <br />      object = object.__proto__; <br />   } <br />   return false; <br />}</pre></a><a name="1044450">With this definition, the following expressions are all true: 
<p></p></a><a name="1044472"><pre>instanceOf (chris, Engineer)<br />instanceOf (chris, WorkerBee)<br />instanceOf (chris, Employee)<br />instanceOf (chris, Object)</pre></a><a name="1044483">But this expression is false: 
<p></p></a><a name="1044485"><pre>instanceOf (chris, SalesPerson)</pre></a><a name="Head2;"></a><a name="1044473"><h3>Global Information in Constructors</h3></a><a name="1043952">When you create constructors, you need to be careful if you set global information in the constructor. For example, assume that you want a unique ID to be automatically assigned to each new employee. You could use this definition for <code>Employee</code>: 
<p></p></a><a name="1044006"><pre>var idCounter = 1;</pre></a><a name="1044007"><pre>function Employee (name, dept) {<br />   this.name = name || "";<br />   this.dept = dept || "general";<br />   this.id = idCounter++;<br />}</pre></a><a name="1044018">With this definition, when you create a new <code>Employee</code>, the constructor assigns it the next ID in sequence and then increments the global ID counter. So, if your next statement were: 
<p></p></a><a name="1044030"><pre>victoria = new Employee("Pigbert, Victoria", "pubs")<br />harry = new Employee("Tschopik, Harry", "sales")</pre></a><a name="1044028"><code>victoria.id</code> is 1 and <code>harry.id</code> is 2. At first glance that seems fine. However, <code>idCounter</code> gets incremented every time an <code>Employee</code> object is created, for whatever purpose. If you create the entire <code>Employee</code> hierarchy we've been working with, the <code>Employee</code> constructor is called every time we set up a prototype. That is, assume you have this code: 
<p></p></a><a name="1044070"><pre>var idCounter = 1;</pre></a><a name="1044071"><pre>function Employee (name, dept) {<br />   this.name = name || "";<br />   this.dept = dept || "general";<br />   this.id = idCounter++;<br />}</pre></a><a name="1044074"><pre>function Manager (name, dept, reports) {...}<br />Manager.prototype = new Employee;</pre></a><a name="1044082"><pre>function WorkerBee (name, dept, projs) {...}<br />WorkerBee.prototype = new Employee;</pre></a><a name="1044094"><pre>function Engineer (name, projs, mach) {...}<br />Engineer.prototype = new WorkerBee;</pre></a><a name="1044096"><pre>function SalesPerson (name, projs, quota) {...}<br />SalesPerson.prototype = new WorkerBee;</pre></a><a name="1044101"><pre>mac = new Engineer("Wood, Mac");</pre></a><a name="1044063">Further assume that the definitions we've omitted here have the <code>base</code> property and call the constructor above them in the prototype chain. In this case, by the time the <code>mac</code> object is created, <code>mac.id</code> is 5. 
<p></p></a><a name="1047015">Depending on the application, it may or may not matter that the counter has been incremented these extra times. If you care about the exact value of this counter, one possible solution involves instead using this constructor: 
<p></p></a><a name="1047016"><pre>function Employee (name, dept) {<br />   this.name = name || "";<br />   this.dept = dept || "general";<br />   if (name)<br />      this.id = idCounter++;<br />}</pre></a><a name="1047017">When you create an instance of <code>Employee</code> to use as a prototype, you do not supply arguments to the constructor. Using this definition of the constructor, when you do not supply arguments, the constructor does not assign a value to the id and does not update the counter. Therefore, for an <code>Employee</code> to get an assigned id, you must specify a name for the employee. In our example, <code>mac.id</code> would be 1. 
<p></p></a><a name="Head2;"></a><a name="1039110"><h3>No Multiple Inheritance</h3></a><a name="1044501">Some object-oriented languages allow multiple inheritance. That is, an object can inherit the properties and values from unrelated parent objects. JavaScript does not support multiple inheritance. 
<p></p></a><a name="1044514">As we've already said, inheritance of property values occurs at runtime by JavaScript searching the prototype chain of an object to find a value. Because an object has a single associated prototype, JavaScript cannot dynamically inherit from more than one prototype chain. 
<p></p></a><a name="1044518">In JavaScript you can have a constructor function call more than one other constructor function within it. This gives the illusion of multiple inheritance. For example, consider the following statements: 
<p></p></a><a name="1044499"><pre>function Hobbyist (hobby) {<br />   this.hobby = hobby || "scuba";<br />}</pre></a><a name="1044521"><pre>function Engineer (name, projs, mach, hobby) {<br />   this.base1 = WorkerBee;<br />   this.base1(name, "engineering", projs);<br />   this.base2 = Hobbyist;<br />   this.base2(hobby);<br />   this.projects = mach || "";<br />}<br />Engineer.prototype = new WorkerBee;</pre></a><a name="1044534"><pre>dennis = new Engineer("Doe, Dennis", ["collabra"], "hugo")</pre></a><a name="1044497">Further assume that the definition of <code>WorkerBee</code> is as we've previously seen it. In this case, the dennis object has these properties: 
<p></p></a><a name="1044543"><pre>dennis.name == "Doe, Dennis"<br />dennis.dept == "engineering"<br />dennis.projects == ["collabra"]<br />dennis.machine == "hugo"<br />dennis.hobby == "scuba"</pre></a><a name="1044547">So <code>dennis</code> does get the <code>hobby</code> property from the <code>Hobbyist</code> constructor. However, assume you then add a property to the <code>Hobbyist</code> constructor's prototype: 
<p></p></a><a name="1044565"><pre>Hobbyist.prototype.equipment = ["mask", "fins", "regulator", "bcd"]</pre></a><a name="1044579">The <code>dennis</code> object does not inherit this new property. 
<p></p></a><p align="right"><font size="-2"><i>Last Updated: 12/18/97 15:19:54 </i></font></p><hr size="4" /><p></p><center>Copyright © 1997 <a href="http://home.netscape.com/misc/contact_info.html" target="_top">Netscape Communications Corporation</a></center><p></p><p></p></li>
<img src ="http://www.blogjava.net/mkchen/aggbug/95144.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/mkchen/" target="_blank">海思</a> 2007-01-21 16:19 <a href="http://www.blogjava.net/mkchen/archive/2007/01/21/95144.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>JavaScript 语言特性[转]</title><link>http://www.blogjava.net/mkchen/archive/2007/01/21/95139.html</link><dc:creator>海思</dc:creator><author>海思</author><pubDate>Sun, 21 Jan 2007 07:49:00 GMT</pubDate><guid>http://www.blogjava.net/mkchen/archive/2007/01/21/95139.html</guid><wfw:comment>http://www.blogjava.net/mkchen/comments/95139.html</wfw:comment><comments>http://www.blogjava.net/mkchen/archive/2007/01/21/95139.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/mkchen/comments/commentRss/95139.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/mkchen/services/trackbacks/95139.html</trackback:ping><description><![CDATA[
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr valign="top">
								<td width="100%">
										<h1>
												<span style="COLOR: #999999">跨越边界: </span>JavaScript 语言特性</h1>
										<p id="subtitle">研究编程语言中的“丑小鸭”</p>
										<img class="display-img" height="6" alt="" src="http://www.ibm.com/i/c.gif" width="1" />
								</td>
								<td class="no-print" width="192">
										<img height="18" alt="developerWorks" src="http://www.ibm.com/developerworks/cn/i/dw.gif" width="192" />
								</td>
						</tr>
				</tbody>
		</table>
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr valign="top">
								<td width="10">
										<img height="1" alt="" src="http://www.ibm.com/i/c.gif" width="10" />
								</td>
								<td width="100%">
										<table class="no-print" cellspacing="0" cellpadding="0" width="160" align="right" border="0">
												<tbody>
														<tr>
																<td width="10">
																		<img height="1" alt="" src="http://www.ibm.com/i/c.gif" width="10" />
																</td>
																<td>
																		<table cellspacing="0" cellpadding="0" width="150" border="0">
																				<tbody>
																						<tr>
																								<td class="v14-header-1-small">文档选项</td>
																						</tr>
																				</tbody>
																		</table>
																		<table class="v14-gray-table-border" cellspacing="0" cellpadding="0" border="0">
																				<tbody>
																						<tr>
																								<td class="no-padding" width="150">
																										<table cellspacing="0" cellpadding="0" width="143" border="0">
																												<img height="1" alt="" src="http://www.ibm.com/i/c.gif" width="8" />
																												<form name="email" action="https://www.ibm.com/developerworks/secure/email-it.jsp">
																														<input type="hidden" value="JavaScript 常被人们认为是编程语言中无足轻重的一员。这种观点的形成可以“归功”于其开发工具、复杂且不一致的面向 HTML 页面的文档对象模型以及不一致的浏览器实现。但 JavaScript 绝对不仅仅是一个玩具这么简单。在本文中，Bruce Tate 向您介绍了 JavaScript 的语言特性。" name="body" />
																														<input type="hidden" value="跨越边界: JavaScript 语言特性" name="subject" />
																														<input type="hidden" value="cn" name="lang" />
																														<script language="JavaScript" type="text/javascript">
																																<!--
document.write('<tr valign="top"><td width="8"><img src="//www.ibm.com/i/c.gif" width="8" height="1" alt=""/></td><td width="16"><img src="//www.ibm.com/i/v14/icons/em.gif" height="16" width="16" vspace="3" alt="将此页作为电子邮件发送" /></td><td width="122"><p><a class="smallplainlink" href="javascript:document.email.submit();"><b>将此页作为电子邮件发送</b></a></p></td></tr>');
//-->
																														</script>
																														<tbody>
																																<tr valign="top">
																																		<td width="8">
																																				<img height="1" alt="" src="http://www.ibm.com/i/c.gif" width="8" />
																																		</td>
																																		<td width="16">
																																				<img height="16" alt="将此页作为电子邮件发送" src="http://www.ibm.com/i/v14/icons/em.gif" width="16" vspace="3" />
																																		</td>
																																		<td width="122">
																																				<p>
																																						<a class="smallplainlink" href="javascript:document.email.submit();">
																																								<b>
																																										<font color="#5c81a7" size="2">将此页作为电子邮件发送</font>
																																								</b>
																																						</a>
																																				</p>
																																		</td>
																																</tr>
																																<noscript>
																																		<tr valign="top">
																																				<td width="8">
																																						<img alt="" height="1" width="8" src="//www.ibm.com/i/c.gif" />
																																				</td>
																																				<td width="16">
																																						<img alt="" width="16" height="16" src="//www.ibm.com/i/c.gif" />
																																				</td>
																																				<td class="small" width="122">
																																						<p>
																																								<span class="ast">未显示需要 JavaScript 的文档选项</span>
																																						</p>
																																				</td>
																																		</tr>
																																</noscript>
																														</tbody>
																												</form>
																												<tr valign="top">
																														<td width="8">
																																<font color="#5c81a7" size="2">
																																		<img height="1" alt="" src="http://www.ibm.com/i/c.gif" width="8" />
																																</font>
																														</td>
																														<td width="16">
																																<font color="#5c81a7" size="2">
																																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/dn.gif" width="16" vspace="3" border="0" />
																																</font>
																														</td>
																														<td width="122">
																																<p>
																																		<a class="smallplainlink" href="http://www.ibm.com/developerworks/cn/java/j-cb12196/index.html?S_TACT=105AGX52&amp;S_CMP=techcsdn#download">
																																				<b>
																																						<font color="#996699" size="2">样例代码</font>
																																				</b>
																																		</a>
																																</p>
																														</td>
																												</tr>
																										</table>
																								</td>
																						</tr>
																				</tbody>
																		</table>
																</td>
														</tr>
												</tbody>
										</table>
										<!--START RESERVED FOR FUTURE USE INCLUDE FILES-->
										<!-- 03/20/06 updated by gretchen -->
										<br />
										<table cellspacing="0" cellpadding="0" width="150" border="0">
												<tbody>
														<tr>
																<td class="v14-header-2-small">拓展 Tomcat 应用</td>
														</tr>
												</tbody>
										</table>
										<table class="v14-gray-table-border" cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td class="no-padding" width="150">
																		<table cellspacing="0" cellpadding="0" width="143" border="0">
																				<tbody>
																						<tr valign="top">
																								<td width="8">
																										<img height="1" alt="" src="http://www.ibm.com/i/c.gif" width="8" />
																								</td>
																								<td>
																										<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/fw_bold.gif" width="16" vspace="3" border="0" />
																								</td>
																								<td width="125">
																										<p>
																												<a class="smallplainlink" href="http://www.ibm.com/developerworks/cn/kickstart/webserver.html?S_TACT=105AGX52&amp;S_CMP=simpleart">
																														<font color="#5c81a7" size="2">下载 IBM 开源 J2EE 应用服务器 WAS CE 新版本 V1.1</font>
																												</a>
																										</p>
																								</td>
																						</tr>
																				</tbody>
																		</table>
																</td>
														</tr>
												</tbody>
										</table>
										<!--END RESERVED FOR FUTURE USE INCLUDE FILES-->
										<br />
								</td>
						</tr>
				</tbody>
		</table>
		<p>级别: 初级</p>
		<p>
				<a href="http://www.ibm.com/developerworks/cn/java/j-cb12196/index.html?S_TACT=105AGX52&amp;S_CMP=techcsdn#author">
						<font color="#996699">Bruce Tate</font>
				</a> (<a href="mailto:bruce.tate@j2life.com?subject=JavaScript 语言特性&amp;cc=bruce.tate@j2life.com"><font color="#5c81a7">bruce.tate@j2life.com</font></a>), 总裁, RapidRed<br /></p>
		<p>2007 年 1 月 18 日</p>
		<blockquote>JavaScript 常被人们认为是编程语言中无足轻重的一员。这种观点的形成可以“归功”于其开发工具、复杂且不一致的面向 HTML 页面的文档对象模型以及不一致的浏览器实现。但 JavaScript 绝对不仅仅是一个玩具这么简单。在本文中，Bruce Tate 向您介绍了 JavaScript 的语言特性。 </blockquote>
		<!--START RESERVED FOR FUTURE USE INCLUDE FILES-->
		<!-- include java script once we verify teams wants to use this and it will work on dbcs and cyrillic characters -->
		<!--END RESERVED FOR FUTURE USE INCLUDE FILES-->
		<p>几乎每个 Web 开发人员都曾有过诅咒 JavaScript 的经历。这个备受争议的语言受累于其复杂的称为文档对象模型 (DOM)的编程模型、糟糕的实现和调试工具以及不一致的浏览器实现。直到最近，很多开发人员还认为 Javascript 从最好的方面说是无可避免之灾祸，从最坏的方面说不过是一种玩具罢了。 </p>
		<p>然而 JavaScript 现在开始日益重要起来，而且成为了广泛应用于 Web 开发的脚本语言。JavaScript 的复苏使一些业界领袖人物也不得不开始重新审视这种编程语言。诸如 Ajax (Asynchronous JavaScript + XML) 这样的编程技术让 Web 网页更加迷人。而完整的 Web 开发框架，比如 Apache Cocoon，则让 JavaScript 的应用越来越多，使其不只限于是一种用于制作 Web 页面的简单脚本。JavaScript 的一种称为 ActionScript 的派生物也推动了 Macromedia 的 Flash 客户端框架的发展。运行在 JVM 上的实现 Rhino 让 JavaScript 成为了 Java™ 开发人员所首选的一类脚本语言（参见 <a href="http://www.ibm.com/developerworks/cn/java/j-cb12196/index.html?S_TACT=105AGX52&amp;S_CMP=techcsdn#resources"><font color="#996699">参考资料</font></a>）。 </p>
		<p>我的好友兼同事 Stuart Halloway 是 Ajax 方面的专家，曾在其教授的 JavaScript 课程中做过这样的开场白：“到 2011 年，JavaScript 将被公认为是一种拥有开发现代应用程序所需的一整套新特性的语言” 。他继而介绍说 JavaScript 程序要比类似的 Java 程序紧密十倍，并继续展示了使其之所以如此的一些语言特性。 </p>
		<table cellspacing="0" cellpadding="0" width="40%" align="right" border="0">
				<tbody>
						<tr>
								<td width="10">
										<img height="1" alt="" src="http://www.ibm.com/i/c.gif" width="10" />
								</td>
								<td>
										<table cellspacing="0" cellpadding="5" width="100%" border="1">
												<tbody>
														<tr>
																<td bgcolor="#eeeeee">
																		<a name="N1007A">
																				<b>关于这个系列</b>
																		</a>
																		<br />
																		<p>在 <a href="http://www.ibm.com/developerworks/cn/java/j-cb/"><font color="#5c81a7">跨越边界系列中</font></a>，作者 Bruce Tate 提出了这样一个主张：今天的 Java 程序员通过学习其他技术和语言，会得到很好的帮助。编程领域已经发生了变化，Java 技术不再是所有开发项目理所当然的最佳选择。其他框架正在影响 Java 框架构建的方式，而从其他语言学到的概念也有助于 Java 编程。对 Python（或 Ruby、Smalltalk 等等）代码的编写可能改变 Java 编码的方式。</p>
																		<p>这个系列介绍的编程概念和技术，与 Java 开发有根本的不同，但可以直接应用于 Java 编程。在某些情况下，需要集成这些技术来利用它们。在其他情况下，可以直接应用这些概念。单独的工具并不重要，重要的是其他语言和框架可以影响 Java 社区中的开发人员、框架，甚至是基本方式。 </p>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<p>在这篇文章中，我将带您探究 JavaScript 的一些特性，看看这些特性如何让它如此具有吸引力： </p>
		<ul>
				<li>
						<b>高阶函数：</b> 一个高阶函数可以将函数作为参数，也可以返回一个函数。此特性让 JavaScript 程序员可以用 Java 语言所不能提供的方法来操纵函数。<br /><br /></li>
				<li>
						<b>动态类型：</b>通过延迟绑定，JavaScript 可以更准确和更灵活。<br /><br /></li>
				<li>
						<b>灵活的对象模型：</b>JavaScript 的对象模型使用一种相对不常见的方式进行继承 —— 称为<i>原型</i> —— 而不是 Java 语言中更常见的基于类的对象模型。 </li>
		</ul>
		<p>您可能已经熟悉动态类型模型、高阶函数形式的函数式编程以及开放对象模型这些概念，因为我在其他的<i>跨越边界</i> 系列文章中已经作过相关的介绍。如果您从未进行过任何正式的 JavaScript 开发，您很可能会认为这些特性属于非常复杂的语言，例如 Python、Lisp、Smalltalk 和 Haskell，而绝非像 JavaScript 这样的语言所能提供的。因此，我将用实际的代码示例来说明这些概念。 </p>
		<p>
				<a name="N100B4">
						<span class="atitle">立即开始</span>
				</a>
		</p>
		<p>您无需设置 JavaScript。如果您可以在浏览器中阅读此篇文章，就证明您已经准备就绪了。本文包含的所有编程示例都可以在大多数浏览器内运行。我使用的是 Firefox。 </p>
		<p>用在 <code>&lt;script type='text/javascript'&gt;</code> 和 <code>&lt;/script&gt;</code> 标记之间所包含的 JavaScript 加载简单的 Web 页面。清单 1 可以显示 Hello, World 文本： </p>
		<br />
		<br />
		<a name="N100CC">
				<b>清单 1. Hello, world</b>
		</a>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td class="code-outline">
										<pre class="displaycode">				
&lt;script type='text/javascript'&gt;
alert('Hello, World.')
&lt;/script&gt;
</pre>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>要运行此代码，只需创建一个名为 example1.html 的文件。将清单 1 的代码复制到该文件内，并在浏览器中加载此文件（参看 <a href="http://www.ibm.com/developerworks/cn/java/j-cb12196/index.html?S_TACT=105AGX52&amp;S_CMP=techcsdn#download"><font color="#996699">下载</font></a> 部分以获得本文使用的所有示例 HTML 文件）。注意到每次重载此页面时，该代码都会立即执行。</p>
		<p>
				<code>alert</code> 是个函数调用，只有一个字符串作为参数。图 1 显示了由清单 1 中的代码弹出的警告框，显示文本 “Hello, World”。如果代码在 HTML body 之内（目前并未指定任何 body，但浏览器能接受不规则的 HTML，并且整个页面都默然作为一个 body 被处理）。页面一旦加载，JavaScript 就会立即执行。 </p>
		<br />
		<br />
		<a name="figure1">
				<b>图 1. Hello, world</b>
		</a>
		<br />
		<img height="136" alt="Hello, World." src="http://www.ibm.com/developerworks/cn/java/j-cb12196/figure-1.jpg" width="320" />
		<br />
		<p>如果要延迟执行，可以在 HTML <code>&lt;head&gt;</code> 元素声明 JavaScript 函数，如清单 2 所示： </p>
		<br />
		<br />
		<a name="listing2">
				<b>清单 2. 延迟执行</b>
		</a>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td class="code-outline">
										<pre class="displaycode">				
&lt;head&gt;
    
    &lt;script type='text/javascript'&gt;
        function hello() {
            alert('Hello, World.')
        }
    &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;button onclick="hello();"&gt;Say Hello&lt;/button&gt;
&lt;/body&gt;
</pre>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>将清单 2 中的代码输入到一个 HTML 文件，在浏览器内加载该文件，单击 <b>Say Hello</b> 按钮，结果如图 2 所示：</p>
		<br />
		<br />
		<a name="figure2">
				<b>图 2. 延迟执行</b>
		</a>
		<br />
		<img height="262" alt="延迟执行" src="http://www.ibm.com/developerworks/cn/java/j-cb12196/figure-2.jpg" width="397" />
		<br />
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td>
										<img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" />
										<br />
										<img height="6" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table class="no-print" cellspacing="0" cellpadding="0" align="right">
				<tbody>
						<tr align="right">
								<td>
										<img height="4" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										<br />
										<table cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td valign="center">
																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" border="0" />
																		<br />
																</td>
																<td valign="top" align="right">
																		<a class="fbox" href="http://www.ibm.com/developerworks/cn/java/j-cb12196/index.html?S_TACT=105AGX52&amp;S_CMP=techcsdn#main">
																				<b>
																						<font color="#996699">回页首</font>
																				</b>
																		</a>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<br />
		<p>
				<a name="N10117">
						<span class="atitle">高阶函数</span>
				</a>
		</p>
		<p>从 <a href="http://www.ibm.com/developerworks/cn/java/j-cb12196/index.html?S_TACT=105AGX52&amp;S_CMP=techcsdn#listing2"><font color="#996699">清单 2</font></a>，可以大致体会到一些 JavaScript 在操纵函数方面的能力。将函数名称传递给 HTML <code>button</code> 标记并利用 HTML 的内置事件模型。使用 JavaScript 时，我会经常在变量或数组中存储函数（在本文后面的 <a href="http://www.ibm.com/developerworks/cn/java/j-cb12196/index.html?S_TACT=105AGX52&amp;S_CMP=techcsdn#objectmodels"><font color="#996699">对象模型</font></a> 一节，您会看到 JavaScript 对象模型策略大量使用了此技巧）。例如，查看一下清单 3： </p>
		<br />
		<br />
		<a name="listing3">
				<b>清单 3. 用变量操纵函数</b>
		</a>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td class="code-outline">
										<pre class="displaycode">				
&lt;head&gt;
    
    &lt;script type='text/javascript'&gt;
        hot = function hot() {
            alert('Sweat.')
        }
        cold  = function cold() {
            alert('Shiver.')
        }
        
        function swap() {
            temp = hot
            hot = cold
            cold = temp    
            alert('Swapped.')
        }
    &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;button onclick="hot();"&gt;Hot&lt;/button&gt;
    &lt;button onclick="cold();"&gt;Cold&lt;/button&gt;
    &lt;button onclick="swap();"&gt;Swap&lt;/button&gt;
&lt;/body&gt;
</pre>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>函数是 JavaScript 中的一类对象，可以自由地操纵它们。首先我声明两个函数：<code>hot</code> 和 <code>cold</code>。并分别在不同的变量存储它们。单击 Hot 或 Cold 按钮会调用对应的函数，生成一个告警。接下来，声明另一个函数用来交换 Hot 和 Cold 按钮的值，将此函数与第三个按钮关联，该按钮显示如图 3 所示的告警： </p>
		<br />
		<br />
		<a name="figure3">
				<b>图 3. 操纵函数</b>
		</a>
		<br />
		<img height="172" alt="" src="http://www.ibm.com/developerworks/cn/java/j-cb12196/figure-3.jpg" width="465" />
		<br />
		<p>这个例子说明可以像处理其他变量一样处理函数。C 开发人员很容易将此概念看作是<i>函数指针</i> 功能，但 JavaScript 的高阶函数的功能更为强大。该特性让 JavaScript 程序员能够像处理其他变量类型一样轻松处理动作或函数。</p>
		<p>将函数用作函数的参数，或将函数作为值返回，这些概念属于高阶函数的领域。清单 4 对 <a href="http://www.ibm.com/developerworks/cn/java/j-cb12196/index.html?S_TACT=105AGX52&amp;S_CMP=techcsdn#listing3"><font color="#996699">清单 3</font></a> 做了一点点修改，显示了能返回函数的高阶函数：</p>
		<br />
		<br />
		<a name="N10162">
				<b>清单 4. 高阶函数</b>
		</a>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td class="code-outline">
										<pre class="displaycode">				
&lt;head&gt;

    &lt;script type='text/javascript'&gt;

        function temperature() {
            return current
        }

        hot = function hot() {
            alert('Hot.')
        }

        cold  = function cold() {
            alert('Cold.')
        }

        current = hot

        function swap() {
            if(current == hot) {
              current = cold
            } else {
              current = hot
            }
        }
    &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;button onclick="funct = temperature()();"&gt;Temperature&lt;/button&gt;
    &lt;button onclick="swap();"&gt;Swap&lt;/button&gt;
&lt;/body&gt;
</pre>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>这个例子解决了一个常见问题：如何将更改中的行为附加到用户接口事件？通过高阶函数，这很容易做到。<code>temperature</code> 高阶函数返回 <code>current</code> 的值，而 current 又可以有 <code>hot</code> 或 <code>cold</code> 函数。看一下这个有些陈旧的函数调用：<code>temperature()()</code>。第一组括号用于调用 <code>temperature</code> 函数。第二组括号调用由 <code>temperature</code><i>返回</i> 的函数。图 4 显示了输出：</p>
		<br />
		<br />
		<a name="figure4">
				<b>图 4. 高阶函数</b>
		</a>
		<br />
		<img height="193" alt="高阶函数" src="http://www.ibm.com/developerworks/cn/java/j-cb12196/figure-4.jpg" width="500" />
		<br />
		<p>高阶函数是函数式编程的基础，对比面向对象编程，函数式编程代表了更高级别的抽象。但 JavaScript 的实力并不仅限于高阶函数。JavaScript 的动态类型就极为适合 UI 开发。</p>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td>
										<img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" />
										<br />
										<img height="6" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table class="no-print" cellspacing="0" cellpadding="0" align="right">
				<tbody>
						<tr align="right">
								<td>
										<img height="4" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										<br />
										<table cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td valign="center">
																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" border="0" />
																		<br />
																</td>
																<td valign="top" align="right">
																		<a class="fbox" href="http://www.ibm.com/developerworks/cn/java/j-cb12196/index.html?S_TACT=105AGX52&amp;S_CMP=techcsdn#main">
																				<b>
																						<font color="#996699">回页首</font>
																				</b>
																		</a>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<br />
		<p>
				<a name="N1019D">
						<span class="atitle">动态类型</span>
				</a>
		</p>
		<p>通过静态类型，编译器可以检查参数和变量的值或针对一个给定操作所允许的返回值。其优势是编译器可以做额外的错误检查。而且静态类型还可以为诸如 IDE 这样的工具提供更多信息，带来其他一些特性，比如更好的代码完成功能。但静态类型也存在着如下一些劣势：</p>
		<ul>
				<li>必须提前声明意图，这常常会导致灵活性降低。例如，更改一个 Java 类就会更改类的类型，因而必须重新编译。对比之下，Ruby 允许开放的类，但更改一个 Java 类还是会更改类的类型。<br /><br /></li>
				<li>要实现相同的功能，必须输入更多的代码。例如，必须用参数形式包括进类型信息，必须用函数形式返回值和所有变量的类型。另外，还必须声明所有变量并显式地转化类型。<br /><br /></li>
				<li>静态语言的编译-部署周期要比动态语言的部署周期长，尽管一些工具可被用来在某种程度上缓解这一问题。 </li>
		</ul>
		<p>静态类型更适合用于构建中间件或操作系统的语言中。UI 开发常常需要更高的效率和灵活性，所以更适合采用动态类型。我深知这种做法存在危险。相信使用过 JavaScript 的 Web 开发人员都曾经为编译器本应检测到的错误类型的变量而绞尽脑汁。但它所带来的优势同样不可否认。下面将举例加以说明。</p>
		<p>首先，考虑一个对象的情况。在清单 5 中，创建一个新对象，并访问一个不存在的属性，名为 <code>color</code>：</p>
		<br />
		<br />
		<a name="listing5">
				<b>清单 5. 引入一个属性</b>
		</a>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td class="code-outline">
										<pre class="displaycode">				
&lt;script type='text/javascript'&gt;
    blank_object = new Object();
    blank_object.color = 'blue'
    alert('The color is ' + blank_object.color)
&lt;/script&gt;
</pre>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>当加载并执行此应用程序时，会得到如图 5 所示的结果：</p>
		<br />
		<br />
		<a name="figure5">
				<b>图 5. 引入属性</b>
		</a>
		<br />
		<img height="136" alt=" 引入属性" src="http://www.ibm.com/developerworks/cn/java/j-cb12196/figure-5.jpg" width="320" />
		<br />
		<p>JavaScript 并不会报告 <code>blue</code> 属性不存在的错误。静态类型的拥护者大都会被本例所吓倒，因为本例中的错误被很好地隐匿了。虽然这种做法多少会让您感觉有些不正当，但您也不能否认它巨大的诱惑力。您可以很快引入属性。如果将本例和本文之前的例子结合起来，还可以引入行为。记住，变量可以保存函数！所以，基于动态类型和高阶函数，您可以在任何时候向类中引入任意的行为。 </p>
		<p>可以轻松地重写 <a href="http://www.ibm.com/developerworks/cn/java/j-cb12196/index.html?S_TACT=105AGX52&amp;S_CMP=techcsdn#listing5"><font color="#996699">清单 5</font></a>，使其如清单 6 所示：</p>
		<br />
		<br />
		<a name="N101F3">
				<b>清单 6. 引入行为</b>
		</a>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td class="code-outline">
										<pre class="displaycode">				
&lt;script type='text/javascript'&gt;
    blank_object = new Object();
    blank_object.color = function() { return 'blue'}
    alert('The color is ' + blank_object.color())
&lt;/script&gt;
</pre>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>从上例可以看出，在 JavaScript 的不同概念之间可以如此轻松地来回变换，其含义上的变化很大 —— 比如，是引入行为还是引入数据 —— 但语法上的变化却很小。该语言很好的延展性是它的一种优势，但同样也是其缺点所在。实际上，该语言本身的对象模型就是 JavaScript 延展程度的一种体现。</p>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td>
										<img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" />
										<br />
										<img height="6" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table class="no-print" cellspacing="0" cellpadding="0" align="right">
				<tbody>
						<tr align="right">
								<td>
										<img height="4" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										<br />
										<table cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td valign="center">
																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" border="0" />
																		<br />
																</td>
																<td valign="top" align="right">
																		<a class="fbox" href="http://www.ibm.com/developerworks/cn/java/j-cb12196/index.html?S_TACT=105AGX52&amp;S_CMP=techcsdn#main">
																				<b>
																						<font color="#996699">回页首</font>
																				</b>
																		</a>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<br />
		<p>
				<a name="objectmodels">
						<span class="atitle">对象模型</span>
				</a>
		</p>
		<p>到目前为止，您应该对 JavaScript 有一个正确的评价了，它绝非只如一个玩具那么简单。事实上，很多人都使用过其对象模型创建过极为复杂、设计良好的面向对象软件。但对象模型尤其是用于继承的对象模型又非您一贯认为的那样。 </p>
		<p>Java 语言是基于类的。当构建应用程序时，也同时构建了可以作为所有对象的模板的新类。然后调用 <code>new</code> 来实例化该模板，创建一个新对象。而在 JavaScript 中，所创建的是一个原型，此原型是一个实例，可以创建所有未来的对象。 </p>
		<p>现在先暂且放下这些抽象的概念，去查看一些实际代码。比如，清单 7 创建了一个简单的 <code>Animal</code>，它具有 <code>name</code> 属性和 <code>speak</code> 动作。其他动物会从这个基础继承。 </p>
		<br />
		<br />
		<a name="listing7">
				<b>清单 7. 创建一个构造函数</b>
		</a>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td class="code-outline">
										<pre class="displaycode">				
&lt;script type='text/javascript'&gt;        
Animal = function() {
    this.name = "nobody"
    this.speak = function () {
        return "Who am I?"
    }
}

myAnimal = new Animal();
alert('The animal named ' + myAnimal.name + 
      ' says ' + myAnimal.speak());

&lt;/script&gt;
</pre>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>清单 7 的结果如图 6 所示：</p>
		<br />
		<br />
		<a name="figure6">
				<b>图 6. 创建一个构造函数</b>
		</a>
		<br />
		<img height="135" alt="构造函数" src="http://www.ibm.com/developerworks/cn/java/j-cb12196/figure-6.jpg" width="383" />
		<br />
		<p>对于 Java 开发人员而言，清单 7 中的代码看起来多少有点生疏和奇怪。实际上对于没有亲自构建过对象的许多 JavaScript 开发人员来说，这些代码同样看起来有点生疏和奇怪。也许，下面的解释可以让大家能够更好地理解这段代码。 </p>
		<p>实际上，您只需重点关注其中三段信息。首先，JavaScript 用嵌套函数表示对象。这意味着清单 7 中的 <code>Animal</code> 的定义是一种有效的语法。第二，JavaScript 基于原型或现有的对象的实例来构造对象，而非基于类模板。<code>funct()</code> 是一种调用，但 <code>new Animal()</code> 却基于 <code>Animal</code> 内的原型构造一个对象。最后，在 JavaScript 中，对象只是函数和变量的集合。每个对象并不与类型相关，所以可以自由地修改这种结构。 </p>
		<p>回到 <a href="http://www.ibm.com/developerworks/cn/java/j-cb12196/index.html?S_TACT=105AGX52&amp;S_CMP=techcsdn#listing7"><font color="#996699">清单 7</font></a>。如您所见，JavaScript 基于在 <code>Animal</code> 中指定的原型定义一个新对象：<code>myAnimal</code>。继而可以使用原型中的属性和函数，甚或重定义函数和属性。这种灵活性可能会让 Java 开发人员受不了，因为他们不习惯这种行为，但它的确是一种十分强大的模型。</p>
		<p>现在我还要更深入一步。您还可以使用名为 <code>prototype</code> 实例变量来指定对象的基础。方法是设置 <code>prototype</code> 实例变量使其指向继承链的父。如此设置 <code>prototype</code> 之后，您所创建的对象会为未指定的那些对象继承属性和函数。这样一来，您就可以模仿面向对象的继承概念。以清单 8 为例： </p>
		<br />
		<br />
		<a name="N10271">
				<b>清单 8. 通过原型继承</b>
		</a>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td class="code-outline">
										<pre class="displaycode">				
&lt;script type='text/javascript'&gt;        

Animal = function() {
    this.name = "nobody"
    this.speak = function () {
        return "Who am I?"
    }
}
Dog = function() {
  this.speak = function() {
    return "Woof!"
  }
}
Dog.prototype = new Animal();

myAnimal = new Dog();
alert('The animal named ' + myAnimal.name + 
      ' says ' + myAnimal.speak());
      &lt;/script&gt;
</pre>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>在清单 8 中，创建了一个 <code>Dog</code> 原型。此原型基于 <code>Animal</code>。<code>Dog</code> 重定义 <code>speak()</code> 方法但却不会对 <code>name()</code> 方法做任何改动。随后，将原型 <code>Dog</code> 设置成 <code>Animal</code>。图 7 显示了其结果：</p>
		<br />
		<br />
		<a name="figure7">
				<b>图 7. 通过原型继承</b>
		</a>
		<br />
		<img height="135" alt="继承" src="http://www.ibm.com/developerworks/cn/java/j-cb12196/figure-7.jpg" width="355" />
		<br />
		<p>这也展示了 JavaScript 是如何解决到属性或方法的引用问题的：</p>
		<ul>
				<li>JavaScript 基于原始的原型创建实例，该原型在构造函数中定义。任何对方法或属性的引用都会使用所生成的原始副本。<br /><br /></li>
				<li>您可以在对象内像定义其他任何变量一样重新定义这些变量。这样做必然会更改此对象。所以您显式定义的任何属性或函数都将比在原始的原型中定义的那些属性或函数优先级要高。<br /><br /></li>
				<li>如果您显式设置了名为 <code>prototype</code> 的实例变量，JavaScript 就会在此实例中寻找任何未定义的实例变量或属性。这种查找是递归的：如果 在 <code>prototype</code> 内定义的实例不能找到属性或函数，它就会在<i>其</i> 原型中查找，依此类推。 </li>
		</ul>
		<p>那么，JavaScript 的继承模型到底是什么样的？这取决于您如何对它进行定义。您需要定义继承行为以便可以覆盖它。然而，从本质上讲，JavaScript 更像是一种函数式语言，而非面向对象的语言，它使用一些智能的语法和语义来仿真高度复杂的行为。其对象模型极为灵活、开放和强大，具有全部的反射性。有些人可能会说它太过灵活。而我的忠告则是，按具体作业的需要选择合适的工具。</p>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td>
										<img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" />
										<br />
										<img height="6" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table class="no-print" cellspacing="0" cellpadding="0" align="right">
				<tbody>
						<tr align="right">
								<td>
										<img height="4" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										<br />
										<table cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td valign="center">
																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" border="0" />
																		<br />
																</td>
																<td valign="top" align="right">
																		<a class="fbox" href="http://www.ibm.com/developerworks/cn/java/j-cb12196/index.html?S_TACT=105AGX52&amp;S_CMP=techcsdn#main">
																				<b>
																						<font color="#996699">回页首</font>
																				</b>
																		</a>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<br />
		<p>
				<a name="N102CB">
						<span class="atitle">结束语</span>
				</a>
		</p>
		<p>JavaScript 对象模型构建在该语言的其他功能之上来支持大量的库，比如 Dojo（参见 <a href="http://www.ibm.com/developerworks/cn/java/j-cb12196/index.html?S_TACT=105AGX52&amp;S_CMP=techcsdn#resources"><font color="#996699">参考资料</font></a>）。这种灵活性让每个框架能够以一种精细的方式更改对象模型。在某种程度上，这种灵活性是一种极大的缺点。它可以导致可怕的互操作性问题（尽管该语言的灵活性可以部分缓解这些问题）。 </p>
		<p>而另一方面，灵活性又是一种巨大的优势。Java 语言一直苦于无法充分增强其灵活性，原因是它的基本对象模型还未灵活到可以被扩展的程度。一个典型的企业级开发人员为能够成功使用 Java 语言必须要学习很多东西，而新出现的一些优秀的开放源码项目和新技术，比如面向方面编程、Spring 编程框架和字节码增强库，则带来了大量要学的代码。 </p>
		<p>最后，JavaScript 优秀的灵活性的确让您体会到了一些高阶语言的强大功能。当然您无需选择为每个项目或大多数项目都做这样的权衡和折衷。但了解一种语言的优势和劣势 —— 通过参考大量信息，而不仅仅基于广告宣传或公众意见 —— 会让您可以更好地控制何时需要使用以及何时不能使用这种语言。当您在修改 JavaScript Web 小部件时，您至少知道该如何让此语言发挥它最大的优势。请继续跨越边界吧。</p>
		<br />
		<p>
				<a name="resources">
						<span class="atitle">参考资料 </span>
				</a>
		</p>
		<b>学习</b>
		<br />
		<ul>
				<li>您可以参阅本文在 developerWorks 全球站点上的 <a href="http://www.ibm.com/developerworks/java/library/j-cb12196/?S_TACT=105AGX52&amp;S_CMP=cn-a-j" target="_blank"><font color="#5c81a7">英文原文</font></a> 。<br /><br /></li>
				<li>
						<a href="http://www.pragmaticprogrammer.com/titles/fr_j2r/index.html">
								<font color="#5c81a7">
										<i>Java To Ruby: Things Every Manager Should Know</i>
								</font>
						</a>（Pragmatic Bookshelf，2006 年）：本文作者所著的书，介绍了何时何地可以从 Java 编程转换到 Ruby on Rails，以及如何进行转换。 <br /><br /></li>
				<li>
						<a href="http://www.oreilly.com/catalog/beyondjava/index.html">
								<font color="#5c81a7">
										<i>Beyond Java</i>
								</font>
						</a>（O'Reilly，2005 年）：本文作者所著的书，介绍了 Java 的兴起和兴盛，以及能够在某些领域挑战 Java 平台的技术。 <br /><br /></li>
				<li>
						<a href="http://script.aculo.us/">
								<font color="#5c81a7">Scriptaculous</font>
						</a> 和 <a href="http://prototype.conio.net/"><font color="#5c81a7">Prototype</font></a>：两种 JavaScript 框架，通过 Ruby on Rails 助力 Ajax。<br /><br /></li>
				<li>
						<a href="http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/index.htm">
								<font color="#996699">Object Hierarchy and Inheritance in JavaScript</font>
						</a>：有关 JavaScript 继承的很好资源。 <br /><br /></li>
				<li>
						<a href="http://ajaxian.com/">
								<font color="#5c81a7">Ajaxian</font>
						</a>：这个 Ajax 的门户网站上有所有有关 Ajax 的杰出讨论，极大地推动了 JavaScript 的复苏。 <br /><br /></li>
				<li>
						<a href="http://dojotoolkit.org/">
								<font color="#5c81a7">Dojo</font>
						</a>：一个 JavaScript 开放源码工具箱。<br /><br /></li>
				<li>
						<a href="http://www.mozilla.org/rhino/">
								<font color="#5c81a7">Rhino</font>
						</a>：JVM 上的 JavaScript 引擎。<br /><br /></li>
				<li>
						<a href="http://www.ibm.com/developerworks/cn/web/wa-javascript.html">
								<font color="#5c81a7">用函数式编程技术编写优美的 JavaScript</font>
						</a>（developerWorks，2006 年 7 月）：作者解释了如何使用 JavaScript(TM)™（JavaScript 能导入函数式编程的构造和特性）编写优美的代码。<br /><br /></li>
				<li>
						<a href="http://www.ibm.com/developerworks/cn/java/">
								<font color="#5c81a7">Java 技术专区</font>
						</a>：数百篇 Java 编程各方面的文章。<br /><br /></li>
				<li>
						<a href="http://www.ibm.com/developerworks/cn/ajax">
								<font color="#5c81a7">Ajax 技术资源中心</font>
						</a>：获得 developerWorks 上有关 Ajax 的所有信息。</li>
		</ul>
<img src ="http://www.blogjava.net/mkchen/aggbug/95139.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/mkchen/" target="_blank">海思</a> 2007-01-21 15:49 <a href="http://www.blogjava.net/mkchen/archive/2007/01/21/95139.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>