??xml version="1.0" encoding="utf-8" standalone="yes"?>亚洲无码视频在线,亚洲乱码日产一区三区,小说区亚洲自拍另类http://m.tkk7.com/mkchen/category/19388.html用开攄脑子去闯?用开阔的视野L?用^和的w心ȝl?用美好的理想去追?zh-cnFri, 02 Mar 2007 06:38:17 GMTFri, 02 Mar 2007 06:38:17 GMT60Object Hierarchy and Inheritance in JavaScripthttp://m.tkk7.com/mkchen/archive/2007/01/21/95144.htmlh?/dc:creator>h?/author>Sun, 21 Jan 2007 08:19:00 GMThttp://m.tkk7.com/mkchen/archive/2007/01/21/95144.htmlhttp://m.tkk7.com/mkchen/comments/95144.htmlhttp://m.tkk7.com/mkchen/archive/2007/01/21/95144.html#Feedback0http://m.tkk7.com/mkchen/comments/commentRss/95144.htmlhttp://m.tkk7.com/mkchen/services/trackbacks/95144.html

Object Hierarchy and Inheritance in JavaScript

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 PDF file or a Microsoft Word self-extracting binary).

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 Chapter 10, "Object Model," in the JavaScript Guide.

The sections in this paper are:

Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances. A class 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 Employee class could represent the set of all employees. An instance, on the other hand, is the instantiation of a class; that is, one of its members. For example, Victoria could be an instance of the Employee class, representing a particular individual as an employee. An instance has exactly the properties of its parent class (no more, no less).

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 prototypical object, 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 prototype for another object, allowing the second object to share the first object's properties.

In class-based languages, you define a class in a separate class definition. In that definition you can specify special methods, called constructors, 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 new operator in association with the constructor method to create class instances.

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 new operator with a constructor function to create a new object.

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 subclass 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 Employee class includes only name and dept properties and Manager is a subclass of Employee that adds the reports property. In this case, an instance of the Manager class would have all three properties: name, dept, and reports.

JavaScript implements inheritance by allowing you to associate a prototypical object with any constructor function. So, you can create exactly the Employee-Manager example, but you use slightly different terminology. First you define the Employee constructor function, specifying the name and dept properties. Next, you define the Manager constructor function, specifying the reports property. Finally, you assign a new Employee object as the prototype for the Manager constructor function. Then, when you create a new Manager, it inherits the name and dept properties from the Employee object.

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.

Table 1 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.

Table 1 Comparison of class-based (Java) and prototype-based (JavaScript) object systems

Class-based (Java) Prototype-based (JavaScript)
Class and instance are distinct entities.

All objects are instances.

Define a class with a class definition; instantiate a class with constructor methods.

Define and create a set of objects with constructor functions.

Create a single object with the new operator.

Same.

Construct an object hierarchy by using class definitions to define subclasses of existing classes.

Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.

Inherit properties by following the class chain.

Inherit properties by following the prototype chain.

Class definition specifies all properties of all instances of a class. No way to add properties dynamically at runtime.

Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.

The Employee Example

The rest of this paper works with the simple employee hierarchy shown in Figure 1.

Figure 1    A simple object hierarchy

  • Employee has the properties name (whose value defaults to the empty string) and dept (whose value defaults to "general").
  • Manager is based on Employee. It adds the reports property (whose value defaults to an empty array, intended to have an array of Employee objects as its value).

  • WorkerBee is also based on Employee. It adds the projects property (whose value defaults to an empty array, intended to have an array of strings as its value).

  • SalesPerson is based on WorkerBee. It adds the quota property (whose value defaults to 100). It also overrides the dept property with the value "sales", indicating that all salespersons are in the same department.

  • Engineer is based on WorkerBee. It adds the machine property (whose value defaults to the empty string) and also overrides the dept property with the value "engineering".

    Creating the Hierarchy

    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.

    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. Figure 2 illustrates the hierarchy with these simple definitions.

    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 . For now, these simple definitions let us look at how the inheritance occurs.

    Figure 2    What the definitions look like

    The simple Java and JavaScript Employee 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.

    JavaScript Java
    function Employee () {
    this.name = "";
    this.dept = "general";
    }
    public class Employee {
       public String name;
       public String dept;
       public Employee () {
          this.name = "";
          this.dept = "general";
       }
    }

    The Manager 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 prototype 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.

    JavaScript Java
    function Manager () {
    this.reports = [];
    }
    Manager.prototype = new Employee;
    function WorkerBee () {
    this.projects = [];
    }
    WorkerBee.prototype = new Employee;
    public class Manager extends Employee {
       public Employee[] reports;
       public Manager () {
          this.reports = new Employee[0];
       }
    }
    public class WorkerBee extends Employee {
       public String[] projects;
       public WorkerBee () {
          this.projects = new String[0];
       }
    }

    The Engineer and SalesPerson definitions create objects that descend from WorkerBee and hence from Employee. 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 dept property with new values specific to these objects.

    JavaScript Java
    function SalesPerson () {
       this.dept = "sales";
       this.quota = 100;
    }
    SalesPerson.prototype = new WorkerBee;
    function Engineer () {
       this.dept = "engineering";
       this.machine = "";
    }
    Engineer.prototype = new WorkerBee;
    public class SalesPerson extends WorkerBee {
       public double quota;
       public SalesPerson () {
          this.dept = "sales";
          this.quota = 100.0;
       }
    }
    public class Engineer extends WorkerBee {
       public String machine;
       public Engineer () {
          this.dept = "engineering";
          this.machine = "";
       }
    }

    Using these definitions, you can create instances of these objects that get the default values for their properties. Figure 3 illustrates using these JavaScript definitions to create new objects and shows the property values for the new objects.

    NOTE: As described earlier, the term instance 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 jane is an instance of Engineer. Similarly, although the terms parent, child, ancestor, and descendant do not have formal meanings in JavaScript, we can use them informally to refer to objects higher or lower in the prototype chain.
    Figure 3    Creating objects with the simple definitions

    Object Properties

    This section discusses how objects inherit properties from other objects in the prototype chain and what happens when you add a property at runtime.

    Inheriting Properties

    Assume you create the mark object as a WorkerBee as shown in Figure 3 with this statement:

    mark = new WorkerBee;
    When JavaScript sees the new operator, it creates a new generic object and passes this new object as the value of the this keyword to the WorkerBee constructor function. The constructor function explicitly sets the value of the projects property. It also sets the value of the internal __proto__ property to the value of WorkerBee.prototype. (That property name has 2 underscore characters at the front and 2 at the end.) The __proto__ 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 mark to that object.

    This process doesn't explicitly put values in the mark object (local values) for the properties mark 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 __proto__ 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 mark object has the following properties and values:

    mark.name = "";
    mark.dept = "general";
    mark.projects = [];
    The mark object inherits values for the name and dept properties from the prototypical object in mark.__proto__. It is assigned a local value for the projects property by the WorkerBee constructor. Simply put, this gives you inheritance of properties and their values in JavaScript. Some subtleties of this process are discussed in .

    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 WorkerBee. You can, of course, change the values of any of these properties. So, you could give specific information for mark as shown here:

    mark.name = "Doe, Mark";
    mark.dept = "admin";
    mark.projects = ["navigator"];

    Adding Properties

    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:

    mark.bonus = 3000;
    Now, the mark object has a bonus property, but no other WorkerBee has this property.

    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 specialty property to all employees with the following statement:

    Employee.prototype.specialty = "none";
    As soon as JavaScript executes this statement, the mark object also has the specialty property with the value of "none". Figure 4 shows the effect of adding this property to the Employee prototype and then overriding it for the Engineer prototype.

    Figure 4    Adding properties

    More Flexible Constructors

    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. Figure 5 shows one way to do this.

    Figure 5    Specifying properties in a constructor, take 1

    Here are the Java and JavaScript definitions for these objects.

    JavaScript Java
    function Employee (name, dept) {
    this.name = name || "";
    this.dept = dept || "general";
    }
    public class Employee {
       public String name;
       public String dept;
       public Employee () {
          this("", "general");
       }
       public Employee (name) {
          this(name, "general");
       }
       public Employee (name, dept) {
          this.name = name;
          this.dept = dept;
       }
    }
    function WorkerBee (projs) {
    this.projects = projs || [];
    }
    WorkerBee.prototype = new Employee;
    public class WorkerBee extends Employee {
       public String[] projects;
       public WorkerBee () {
          this(new String[0]);
       }
       public WorkerBee (String[] projs) {
          this.projects = projs;
       }
    }
    function Engineer (mach) {
       this.dept = "engineering";
       this.machine = mach || "";
    }
    Engineer.prototype = new WorkerBee;
    public class Engineer extends WorkerBee {
       public String machine;
       public WorkerBee () {
          this.dept = "engineering";
          this.machine = "";
       }
       public WorkerBee (mach) {
          this.dept = "engineering";
          this.machine = mach;
       }
    }

    These JavaScript definitions use a special idiom for setting default values:

    this.name = name || "";
    The JavaScript logical OR operator (||) 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 name has a useful value for the name property. If it does, it sets this.name to that value. Otherwise, it sets this.name to the empty string. This paper uses this idiom for brevity; however, it can be puzzling at first glance.

    With these definitions, when you create an instance of an object, you can specify values for the locally defined properties. As shown in Figure 5, you can use this statement to create a new Engineer:

    jane = new Engineer("belau");
    Jane's properties are now:

    jane.name == "";
    jane.dept == "general";
    jane.projects == [];
    jane.machine == "belau"
    Notice that with these definitions, you cannot specify an initial value for an inherited property such as name. If you want to specify an initial value for inherited properties in JavaScript, you need to add more code to the constructor function.

    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. Figure 6 shows these new definitions.

    Figure 6    Specifying properties in a constructor, take 2

    Let's look at one of these definitions in detail. Here's the new definition for the Engineer constructor:

    function Engineer (name, projs, mach) {
    this.base = WorkerBee;
    this.base(name, "engineering", projs);
    this.projects = mach || "";
    }
    Assume we create a new Engineer object as follows:

    jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
    JavaScript follows these steps:

    1.   First, the new operator creates a generic object and sets its __proto__ property to Engineer.prototype.
    2.   The new operator then passes the new object to the Engineer constructor as the value of the this keyword.
    3.   Next, the constructor creates a new property called base for that object and assigns the value of the WorkerBee constructor to the base property. This makes the WorkerBee constructor a method of the Engineer object.
    NOTE: The name of the base property is not special. You can use any legal property name; base is simply evocative of its purpose.
    4.   Next, the constructor calls the base method, passing as its arguments two of the arguments passed to the constructor ("Doe, Jane" and ["navigator", "javascript"]) and also the string "engineering". Explicitly using "engineering" in the constructor indicates that all Engineer objects have the same value for the inherited dept property and this value overrides the value inherited from Employee.
    5.   Because base is a method of Engineer, within the call to base, JavaScript binds the this keyword to the object created in step 1. Thus, the WorkerBee function in turn passes the "Doe, Jane" and ["navigator", "javascript"] arguments to the Employee constructor function. Upon return from the Employee constructor function, the WorkerBee function uses the remaining argument to set the projects property.
    6.   Upon return from the base method, the Engineer constructor initializes the object's machine property to "belau".
    7.   Upon return from the constructor, JavaScript assigns the new object to the jane variable.
    You might think that, having called the WorkerBee constructor from inside the Engineer constructor, you've set up inheritance appropriately for Engineer objects. This is not the case. Calling the WorkerBee constructor ensures that an Engineer object starts out with the properties specified in all constructor functions that are called. However, if you later add properties to the Employee or WorkerBee prototypes, those properties are not inherited by the Engineer object. For example, assume you have these statements:

    function Engineer (name, projs, mach) {
    this.base = WorkerBee;
    this.base(name, "engineering", projs);
    this.projects = mach || "";
    }
    jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
    Employee.prototype.specialty = "none";
    The jane object does not inherit the specialty property. You still need to explicitly set up the prototype to ensure dynamic inheritance. Assume instead you have these statements:

    function Engineer (name, projs, mach) {
    this.base = WorkerBee;
    this.base(name, "engineering", projs);
    this.projects = mach || "";
    }
    Engineer.prototype = new WorkerBee;
    jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
    Employee.prototype.specialty = "none";
    Now the value of the jane object's specialty property is "none".

    Property Inheritance Revisited

    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.

    Local versus Inherited Values

    Let's revisit property inheritance briefly. As discussed earlier, when you access an object property, JavaScript performs these steps:

    1. Check to see if the value exists locally. If it does, return that value.
    2. If there isn't a local value, check the prototype chain (using the __proto__ property).

    3. If an object in the prototype chain has a value for the specified property, return that value.

    4. If no such property is found, the object does not have the property.
    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:

    function Employee () {
    this.name = "";
    this.dept = "general";
    }
    function WorkerBee () {
    this.projects = [];
    }
    WorkerBee.prototype = new Employee;
    With these definitions, assume you create amy as an instance of WorkerBee with this statement:

    amy = new WorkerBee;
    The amy object has one local property, projects. The values for the name and dept properties are not local to amy and so are gotten from the amy object's __proto__ property. Thus, amy has these property values:

    amy.name == "";
    amy.dept = "general";
    amy.projects == [];
    Now assume you change the value of the name property in the prototype associated with Employee:

    Employee.prototype.name = "Unknown"
    At first glance, you might expect that new value to propagate down to all the instances of Employee. However, it does not.

    When you create any instance of the Employee object, that instance gets a local value for the name property (the empty string). This means that when you set the WorkerBee prototype by creating a new Employee object, WorkerBee.prototype has a local value for the name property. Therefore, when JavaScript looks up the name property of the amy object (an instance of WorkerBee), JavaScript finds the local value for that property in WorkerBee.prototype. It therefore does not look farther up the chain to Employee.prototype.

    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:

    function Employee () {
       this.dept = "general";
    }
    Employee.prototype.name = "";
    function WorkerBee () {
    this.projects = [];
    }
    WorkerBee.prototype = new Employee;
    amy = new WorkerBee;
    Employee.prototype.name = "Unknown";
    In this case, the name property of amy becomes "Unknown".

    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.

    Determining Instance Relationships

    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 instanceof operator for this purpose. JavaScript does not provide instanceof, but you can write such a function yourself.

    As discussed in , when you use the new operator with a constructor function to create a new object, JavaScript sets the __proto__ property of the new object to the value of the prototype property of the constructor function. You can use this to test the prototype chain.

    For example, assume you have the same set of definitions we've been using, with the prototypes set appropriately. Create an __proto__ object as follows:

    chris = new Engineer("Pigman, Chris", ["jsd"], "fiji");
    With this object, the following statements are all true:

    chris.__proto__ == Engineer.prototype;
    chris.__proto__.__proto__ == WorkerBee.prototype;
    chris.__proto__.__proto__.__proto__ == Employee.prototype;
    chris.__proto__.__proto__.__proto__.__proto__ == Object.prototype;
    chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null;
    Given this, you could write an instanceOf function as follows:

    function instanceOf(object, constructor) { 
       while (object != null) {
          if (object == constructor.prototype)
             return true;
          object = object.__proto__;
       }
       return false;
    }
    With this definition, the following expressions are all true:

    instanceOf (chris, Engineer)
    instanceOf (chris, WorkerBee)
    instanceOf (chris, Employee)
    instanceOf (chris, Object)
    But this expression is false:

    instanceOf (chris, SalesPerson)

    Global Information in Constructors

    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 Employee:

    var idCounter = 1;
    function Employee (name, dept) {
       this.name = name || "";
       this.dept = dept || "general";
       this.id = idCounter++;
    }
    With this definition, when you create a new Employee, the constructor assigns it the next ID in sequence and then increments the global ID counter. So, if your next statement were:

    victoria = new Employee("Pigbert, Victoria", "pubs")
    harry = new Employee("Tschopik, Harry", "sales")
    victoria.id is 1 and harry.id is 2. At first glance that seems fine. However, idCounter gets incremented every time an Employee object is created, for whatever purpose. If you create the entire Employee hierarchy we've been working with, the Employee constructor is called every time we set up a prototype. That is, assume you have this code:

    var idCounter = 1;
    function Employee (name, dept) {
       this.name = name || "";
       this.dept = dept || "general";
       this.id = idCounter++;
    }
    function Manager (name, dept, reports) {...}
    Manager.prototype = new Employee;
    function WorkerBee (name, dept, projs) {...}
    WorkerBee.prototype = new Employee;
    function Engineer (name, projs, mach) {...}
    Engineer.prototype = new WorkerBee;
    function SalesPerson (name, projs, quota) {...}
    SalesPerson.prototype = new WorkerBee;
    mac = new Engineer("Wood, Mac");
    Further assume that the definitions we've omitted here have the base property and call the constructor above them in the prototype chain. In this case, by the time the mac object is created, mac.id is 5.

    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:

    function Employee (name, dept) {
       this.name = name || "";
       this.dept = dept || "general";
       if (name)
          this.id = idCounter++;
    }
    When you create an instance of Employee 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 Employee to get an assigned id, you must specify a name for the employee. In our example, mac.id would be 1.

    No Multiple Inheritance

    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.

    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.

    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:

    function Hobbyist (hobby) {
       this.hobby = hobby || "scuba";
    }
    function Engineer (name, projs, mach, hobby) {
       this.base1 = WorkerBee;
       this.base1(name, "engineering", projs);
       this.base2 = Hobbyist;
       this.base2(hobby);
       this.projects = mach || "";
    }
    Engineer.prototype = new WorkerBee;
    dennis = new Engineer("Doe, Dennis", ["collabra"], "hugo")
    Further assume that the definition of WorkerBee is as we've previously seen it. In this case, the dennis object has these properties:

    dennis.name == "Doe, Dennis"
    dennis.dept == "engineering"
    dennis.projects == ["collabra"]
    dennis.machine == "hugo"
    dennis.hobby == "scuba"
    So dennis does get the hobby property from the Hobbyist constructor. However, assume you then add a property to the Hobbyist constructor's prototype:

    Hobbyist.prototype.equipment = ["mask", "fins", "regulator", "bcd"]
    The dennis object does not inherit this new property.

    Last Updated: 12/18/97 15:19:54


    Copyright © 1997 Netscape Communications Corporation



  • ]]>
    JavaScript 语言Ҏ[转]http://m.tkk7.com/mkchen/archive/2007/01/21/95139.htmlh?/dc:creator>h?/author>Sun, 21 Jan 2007 07:49:00 GMThttp://m.tkk7.com/mkchen/archive/2007/01/21/95139.htmlhttp://m.tkk7.com/mkchen/comments/95139.htmlhttp://m.tkk7.com/mkchen/archive/2007/01/21/95139.html#Feedback0http://m.tkk7.com/mkchen/comments/commentRss/95139.htmlhttp://m.tkk7.com/mkchen/services/trackbacks/95139.html

    跨越边界: JavaScript 语言Ҏ?/h1>

    研究~程语言中的“丑鸭?/p> developerWorks
    文选项
    此作为电子邮件发? src=

    此作为电子邮件发?/font>

    未显C需?JavaScript 的文选项

    样例代码


    拓展 Tomcat 应用

    下蝲 IBM 开?J2EE 应用服务?WAS CE 新版?V1.1


    U别: 初

    Bruce Tate (bruce.tate@j2life.com), 总裁, RapidRed

    2007 q?1 ?18 ?/p>

    JavaScript 常被Z认ؓ是编E语a中无重的一员。这U观点的形成可以“归功”于其开发工兗复杂且不一致的面向 HTML 面的文档对象模型以及不一致的览器实现。但 JavaScript l对不仅仅是一个玩兯么简单。在本文中,Bruce Tate 向您介绍?JavaScript 的语aҎ?

    几乎每个 Web 开发h员都曾有q诅?JavaScript 的经历。这个备受争议的语言受篏于其复杂的称为文对象模?(DOM)的编E模型、糟p的实现和调试工具以及不一致的览器实现。直到最q,很多开发h员还认ؓ Javascript 从最好的斚w说是无可避免之灾,从最坏的斚w说不q是一U玩LŞ了?

    然?JavaScript 现在开始日益重要v来,而且成ؓ了广泛应用于 Web 开发的脚本语言。JavaScript 的复苏一些业界领袖h物也不得不开始重新审视这U编E语a。诸?Ajax (Asynchronous JavaScript + XML) q样的编E技术让 Web |页更加qh。而完整的 Web 开发框Ӟ比如 Apache CocoonQ则?JavaScript 的应用越来越多,使其不只限于是一U用于制?Web 面的简单脚本。JavaScript 的一U称?ActionScript 的派生物也推动了 Macromedia ?Flash 客户端框架的发展。运行在 JVM 上的实现 Rhino ?JavaScript 成ؓ?Java?开发h员所首选的一c脚本语aQ参?参考资?/font>Q?

    我的好友兼同?Stuart Halloway ?Ajax 斚w的专Ӟ曑֜其教授的 JavaScript 评中做q这L开场白Q“到 2011 q_JavaScript 被公认为是一U拥有开发现代应用程序所需的一整套新特性的语言?。他l而介l说 JavaScript E序要比cM?Java E序紧密十倍,ql展CZ使其之所以如此的一些语aҎ?

    关于q个pd

    ?跨越边界pd?/font>Q作?Bruce Tate 提出了这样一个主张:今天?Java E序员通过学习其他技术和语言Q会得到很好的帮助。编E领域已l发生了变化QJava 技术不再是所有开发项目理所当然的最佳选择。其他框架正在媄?Java 框架构徏的方式,而从其他语言学到的概念也有助?Java ~程。对 PythonQ或 Ruby、Smalltalk {等Q代码的~写可能改变 Java ~码的方式?/p>

    q个pd介绍的编E概念和技术,?Java 开发有Ҏ的不同,但可以直接应用于 Java ~程。在某些情况下,需要集成这些技术来利用它们。在其他情况下,可以直接应用q些概念。单独的工具q不重要Q重要的是其他语a和框架可以媄?Java C֌中的开发h员、框Ӟ甚至是基本方式?

    在这文章中Q我带您探I?JavaScript 的一些特性,看看q些Ҏ如何让它如此具有吸引力Q?

    • 高阶函数Q?/b> 一个高阶函数可以将函数作ؓ参数Q也可以q回一个函数。此Ҏ让 JavaScript E序员可以用 Java 语言所不能提供的方法来操纵函数?br />
    • 动态类型:通过延迟l定QJavaScript 可以更准和更灵zR?br />
    • 灉|的对象模型:JavaScript 的对象模型用一U相对不常见的方式进行?—?UCؓ原型 —?而不?Java 语言中更常见的基于类的对象模型?

    您可能已l熟悉动态类型模型、高阶函数Ş式的函数式编E以及开攑֯象模型这些概念,因ؓ我在其他?i>跨越边界 pd文章中已l作q相关的介绍。如果您从未q行qQ何正式的 JavaScript 开发,您很可能会认些特性属于非常复杂的语言Q例?Python、Lisp、Smalltalk ?HaskellQ而绝非像 JavaScript q样的语a所能提供的。因此,我将用实际的代码CZ来说明这些概c?

    立即开?/span>

    您无需讄 JavaScript。如果您可以在浏览器中阅L文章,p明您已经准备qA了。本文包含的所有编E示例都可以在大多数览器内q行。我使用的是 Firefox?

    用在 <script type='text/javascript'> ?</script> 标记之间所包含?JavaScript 加蝲单的 Web 面。清?1 可以昄 Hello, World 文本Q?



    清单 1. Hello, world
    				
    <script type='text/javascript'>
    alert('Hello, World.')
    </script>
    

    要运行此代码Q只需创徏一个名?example1.html 的文件。将清单 1 的代码复制到该文件内Qƈ在浏览器中加载此文gQ参?下蝲 部分以获得本文用的所有示?HTML 文gQ。注意到每次重蝲此页面时Q该代码都会立即执行?/p>

    alert 是个函数调用Q只有一个字W串作ؓ参数。图 1 昄了由清单 1 中的代码弹出的警告框Q显C文?“Hello, World”。如果代码在 HTML body 之内Q目前ƈ未指定Q?bodyQ但览器能接受不规则的 HTMLQƈ且整个页面都默然作ؓ一?body 被处理)。页面一旦加载,JavaScript ׃立即执行?



    ?1. Hello, world
    Hello, World.

    如果要gq执行,可以?HTML <head> 元素声明 JavaScript 函数Q如清单 2 所C:



    清单 2. 延迟执行
    				
    <head>
        
        <script type='text/javascript'>
            function hello() {
                alert('Hello, World.')
            }
        </script>
    </head>
    <body>
        <button onclick="hello();">Say Hello</button>
    </body>
    

    清?2 中的代码输入C?HTML 文gQ在览器内加蝲该文Ӟ单击 Say Hello 按钮Q结果如?2 所C:



    ?2. 延迟执行
    延迟执行




    回页?/font>


    高阶函数

    ?清单 2Q可以大致体会到一?JavaScript 在操U函数方面的能力。将函数名称传递给 HTML button 标记q利?HTML 的内|事件模型。?JavaScript Ӟ我会l常在变量或数组中存储函敎ͼ在本文后面的 对象模型 一节,您会看到 JavaScript 对象模型{略大量使用了此技巧)。例如,查看一下清?3Q?



    清单 3. 用变量操U函?/b>
    				
    <head>
        
        <script type='text/javascript'>
            hot = function hot() {
                alert('Sweat.')
            }
            cold  = function cold() {
                alert('Shiver.')
            }
            
            function swap() {
                temp = hot
                hot = cold
                cold = temp    
                alert('Swapped.')
            }
        </script>
    </head>
    <body>
        <button onclick="hot();">Hot</button>
        <button onclick="cold();">Cold</button>
        <button onclick="swap();">Swap</button>
    </body>
    

    函数?JavaScript 中的一cd象,可以自由地操U它们。首先我声明两个函数Q?code>hot ?cold。ƈ分别在不同的变量存储它们。单?Hot ?Cold 按钮会调用对应的函数Q生成一个告警。接下来Q声明另一个函数用来交?Hot ?Cold 按钮的|此函数与第三个按钮兌Q该按钮昄如图 3 所C的告警Q?



    ?3. 操纵函数

    q个例子说明可以像处理其他变量一样处理函数。C 开发h员很Ҏ此概念看作?i>函数指针 功能Q但 JavaScript 的高阶函数的功能更ؓ强大。该Ҏ让 JavaScript E序员能够像处理其他变量cd一栯村֤理动作或函数?/p>

    函数用作函数的参数Q或函C为D回,q些概念属于高阶函数的领域。清?4 ?清单 3 做了一点点修改Q显CZ能返回函数的高阶函数Q?/p>

    清单 4. 高阶函数
    				
    <head>
    
        <script type='text/javascript'>
    
            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
                }
            }
        </script>
    </head>
    <body>
        <button onclick="funct = temperature()();">Temperature</button>
        <button onclick="swap();">Swap</button>
    </body>
    

    q个例子解决了一个常见问题:如何更改中的行为附加到用户接口事gQ通过高阶函数Q这很容易做到?code>temperature 高阶函数q回 current 的|?current 又可以有 hot ?cold 函数。看一下这个有些陈旧的函数调用Q?code>temperature()()。第一l括L于调?temperature 函数。第二组括号调用?temperatureq回 的函数。图 4 昄了输出:



    ?4. 高阶函数
    高阶函数

    高阶函数是函数式~程的基Q对比面向对象编E,函数式编E代表了更高U别的抽象。但 JavaScript 的实力ƈ不仅限于高阶函数。JavaScript 的动态类型就极ؓ适合 UI 开发?/p>



    回页?/font>


    动态类?/span>

    通过静态类型,~译器可以检查参数和变量的值或针对一个给定操作所允许的返回倹{其优势是编译器可以做额外的错误查。而且静态类型还可以?IDE q样的工h供更多信息,带来其他一些特性,比如更好的代码完成功能。但静态类型也存在着如下一些劣势:

    • 必须提前声明意图Q这常常会导致灵zL降低。例如,更改一?Java cd会更改类的类型,因而必重新编译。对比之下,Ruby 允许开攄c,但更改一?Java c还是会更改cȝcd?br />
    • 要实现相同的功能Q必输入更多的代码。例如,必须用参数Ş式包括进cd信息Q必ȝ函数形式q回值和所有变量的cd。另外,q必d明所有变量ƈ昑ּ地{化类型?br />
    • 静态语a的编?部v周期要比动态语a的部|周期长Q尽一些工具可被用来在某种E度上缓解这一问题?

    静态类型更适合用于构徏中间件或操作pȝ的语a中。UI 开发常帔R要更高的效率和灵zL,所以更适合采用动态类型。我qq种做法存在危险。相信用过 JavaScript ?Web 开发h员都曄为编译器本应到的错误类型的变量而绞脑汁。但它所带来的优势同样不可否认。下面将举例加以说明?/p>

    首先Q考虑一个对象的情况。在清单 5 中,创徏一个新对象Qƈ讉K一个不存在的属性,名ؓ colorQ?/p>

    清单 5. 引入一个属?/b>
    				
    <script type='text/javascript'>
        blank_object = new Object();
        blank_object.color = 'blue'
        alert('The color is ' + blank_object.color)
    </script>
    

    当加载ƈ执行此应用程序时Q会得到如图 5 所C的l果Q?/p>

    ?5. 引入属?/b>
     引入属? src=

    JavaScript q不会报?blue 属性不存在的错误。静态类型的拥护者大都会被本例所吓倒,因ؓ本例中的错误被很好地隐匿了。虽然这U做法多会让您感觉有些不正当,但您也不能否认它巨大的诱惑力。您可以很快引入属性。如果将本例和本文之前的例子l合hQ还可以引入行ؓ。记住,变量可以保存函数Q所以,Z动态类型和高阶函数Q您可以在Q何时候向cM引入L的行为?

    可以L地重?清单 5Q其如清单 6 所C:



    清单 6. 引入行ؓ
    				
    <script type='text/javascript'>
        blank_object = new Object();
        blank_object.color = function() { return 'blue'}
        alert('The color is ' + blank_object.color())
    </script>
    

    从上例可以看出,?JavaScript 的不同概念之间可以如此轻村֜来回变换Q其含义上的变化很大 —?比如Q是引入行ؓq是引入数据 —?但语法上的变化却很小。该语言很好的g展性是它的一U优势,但同样也是其~点所在。实际上Q该语言本n的对象模型就?JavaScript 延展E度的一U体现?/p>



    回页?/font>


    对象模型

    到目前ؓ止,您应该对 JavaScript 有一个正的评h了,它绝非只如一个玩具那么简单。事实上Q很多h都用过其对象模型创极ؓ复杂、设计良好的面向对象软g。但对象模型其是用于承的对象模型又非您一贯认为的那样?

    Java 语言是基于类的。当构徏应用E序Ӟ也同时构Z可以作ؓ所有对象的模板的新cR然后调?new 来实例化该模板,创徏一个新对象。而在 JavaScript 中,所创徏的是一个原型,此原型是一个实例,可以创徏所有未来的对象?

    现在先暂且放下这些抽象的概念Q去查看一些实际代码。比如,清单 7 创徏了一个简单的 AnimalQ它h name 属性和 speak 动作。其他动物会从这个基l承?



    清单 7. 创徏一个构造函?/b>
    				
    <script type='text/javascript'>        
    Animal = function() {
        this.name = "nobody"
        this.speak = function () {
            return "Who am I?"
        }
    }
    
    myAnimal = new Animal();
    alert('The animal named ' + myAnimal.name + 
          ' says ' + myAnimal.speak());
    
    </script>
    

    清单 7 的结果如?6 所C:



    ?6. 创徏一个构造函?/b>
    构造函? src=

    对于 Java 开发h员而言Q清?7 中的代码看v来多有点生疏和奇怪。实际上对于没有亲自构徏q对象的许多 JavaScript 开发h员来_q些代码同样看v来有点生疏和奇怪。也许,下面的解释可以让大家能够更好地理解这D代码?

    实际上,您只需重点x其中三段信息。首先,JavaScript 用嵌套函数表C对象。这意味着清单 7 中的 Animal 的定义是一U有效的语法。第二,JavaScript Z原型或现有的对象的实例来构造对象,而非ZcLѝ?code>funct() 是一U调用,?new Animal() 却基?Animal 内的原型构造一个对象。最后,?JavaScript 中,对象只是函数和变量的集合。每个对象ƈ不与cd相关Q所以可以自由地修改q种l构?

    回到 清单 7。如您所见,JavaScript Z?Animal 中指定的原型定义一个新对象Q?code>myAnimal。而可以用原型中的属性和函数Q甚或重定义函数和属性。这U灵zL可能会?Java 开发h员受不了Q因Z们不习惯q种行ؓQ但它的是一U十分强大的模型?/p>

    现在我还要更深入一步。您q可以用名?prototype 实例变量来指定对象的基础。方法是讄 prototype 实例变量使其指向l承铄父。如此设|?prototype 之后Q您所创徏的对象会为未指定的那些对象承属性和函数。这样一来,您就可以模仿面向对象的承概c以清单 8 ZQ?



    清单 8. 通过原型l承
    				
    <script type='text/javascript'>        
    
    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());
          </script>
    

    在清?8 中,创徏了一?Dog 原型。此原型Z Animal?code>Dog 重定?speak() Ҏ但却不会?name() Ҏ做Q何改动。随后,原?Dog 讄?Animal。图 7 昄了其l果Q?/p>

    ?7. 通过原型l承
    l承

    q也展示?JavaScript 是如何解军_属性或Ҏ的引用问题的Q?/p>

    • JavaScript Z原始的原型创建实例,该原型在构造函C定义。Q何对Ҏ或属性的引用都会使用所生成的原始副本?br />
    • 您可以在对象内像定义其他M变量一样重新定义这些变量。这样做必然会更Ҏ对象。所以您昑ּ定义的Q何属性或函数都将比在原始的原型中定义的那些属性或函数优先U要高?br />
    • 如果您显式设|了名ؓ prototype 的实例变量,JavaScript ׃在此实例中寻找Q何未定义的实例变量或属性。这U查找是递归的:如果 ?prototype 内定义的实例不能扑ֈ属性或函数Q它׃?i>?/i> 原型中查找,依此cL?

    那么QJavaScript 的承模型到底是什么样的?q取决于您如何对它进行定义。您需要定义承行Z便可以覆盖它。然而,从本质上ԌJavaScript 更像是一U函数式语言Q而非面向对象的语aQ它使用一些智能的语法和语义来仿真高度复杂的行为。其对象模型极ؓ灉|、开攑֒强大Q具有全部的反射性。有些h可能会说它太q灵zR而我的忠告则是,按具体作业的需要选择合适的工具?/p>



    回页?/font>


    l束?/span>

    JavaScript 对象模型构徏在该语言的其他功能之上来支持大量的库Q比?DojoQ参?参考资?/font>Q。这U灵zL让每个框架能够以一U精l的方式更改对象模型。在某种E度上,q种灉|性是一U极大的~点。它可以D可怕的互操作性问题(管该语a的灵zL可以部分缓解这些问题)?

    而另一斚wQ灵zL又是一U巨大的优势。Java 语言一直苦于无法充分增强其灉|性,原因是它的基本对象模型还未灵zd可以被扩展的E度。一个典型的企业U开发h员ؓ能够成功使用 Java 语言必须要学习很多东西,而新出现的一些优U的开放源码项目和新技术,比如面向斚w~程、Spring ~程框架和字节码增强库,则带来了大量要学的代码?

    最后,JavaScript 优秀的灵zL的让您体会到了一些高阶语a的强大功能。当然您无需选择为每个项目或大多数项目都做这L权衡和折街但了解一U语a的优势和劣势 —?通过参考大量信息,而不仅仅Zq告宣传或公众意?—?会让您可以更好地控制何时需要用以及何时不能用这U语a。当您在修改 JavaScript Web 部件时Q您臛_知道该如何让此语a发挥它最大的优势。请l箋跨越边界吧?/p>

    参考资?

    学习


    ]]> վ֩ģ壺 һAVٸӰ| 97Ʒѹۿ| ĻƷһ | ޾Ʒ| Ƶ߹ۿ| 337pձŷ޴ɫ| СƵ߹ۿ| ѳ¼Ƶ| ҹδʮվ2| ޳Ļ| ijվ| ձػɫAAAƬ| þ99Ƶ| avվyy| ˿wwwƵ| 91ɫƵ޹ۿ| 2019Ļ| Ƶ߹ۿ| Ƶ̫ˬ| ĻӰԺ| ޵һAVվ| ˳վ߹ۿ| ƷƵ| 97| ҹƷþþþþ˳ | wwwƵѿ| ѹۿһëƬa| ޹ۺһ| ޹ᆱƷԲ߹ۿ| ۺϾƷ˾þ| һƬѿ| һۿƵ߲| ŷ޺ڴ| ѿƬAëƬѿ| Ʒ_Ʒ| vaþþþúݺ| ۺϼ߹ۿ| ɫһۺ| һѹۿƵ | ޻ɫƬ߹ۿ| ߳ëƬڵƵ|