您的搜索结果

    JavaScript面向对象简介

    JavaScript拥有强壮的面向对象编程的能力,即便有一些争议存在,这是因为面向对象的JavaScript与其他语言有一些区别。

    这篇文章从介绍面向对象编程开始,然后仔细研究JavaScript对象模型,最后说明JavaScript中的面向对象编程的概念。

    复习JavaScript

    如果您对JavaScript的概念(如变量、类型、方法和作用域等)没有信心,您可以在A re-introduction to JavaScript这篇文章里学习这些概念。您也可以查阅这篇文章Core JavaScript 1.5 Guide

    Object-oriented programming

    Object-oriented programming is a programming paradigm that uses abstraction to create models based on the real world. It uses several techniques from previously established paradigms, including modularity, polymorphism, and encapsulation. Today, many popular programming languages (such as Java, JavaScript, C#, C++, Python, PHP, Ruby and Objective-C) support object-oriented programming (OOP).

    Object-oriented programming may be seen as the design of software using a collection of cooperating objects, as opposed to a traditional view in which a program may be seen as a collection of functions, or simply as a list of instructions to the computer. In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects. Each object can be viewed as an independent little machine with a distinct role or responsibility.

    Object-oriented programming is intended to promote greater flexibility and maintainability in programming, and is widely popular in large-scale software engineering. By virtue of its strong emphasis on modularity, object oriented code is intended to be simpler to develop and easier to understand later on, lending itself to more direct analysis, coding, and understanding of complex situations and procedures than less modular programming methods.2

    术语

    类 (Class)
    定义对象的特性。
    对象 (Object)
    一个类的实例。
    属性 (Property)
    An Object characteristic, such as color.
    方法 (Method)
    An Object capability, such as walk.
    构造函数 (Constructor)
    A method called at the moment of instantiation.
    继承 (Inheritance)
    A Class can inherit characteristics from another Class.
    封装 (Encapsulation)
    A Class defines only the characteristics of the Object, a method defines only how the method executes.
    抽象 (Abstraction)
    The conjunction of complex inheritance, methods, properties of an Object must be able to simulate a reality model.
    多态 (Polymorphism)
    Different Classes might define the same method or property.

    For a more extensive description of object-oriented programming, see Object-oriented programming at Wikipedia.

    以原型为基础的编程

    Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is accomplished through a process of decorating existing objects which serve as prototypes. This model is also known as class-less, prototype-oriented, or instance-based programming.

    The original (and most canonical) example of a prototype-based language is the programming language Self developed by David Ungar and Randall Smith. However, the class-less programming style has recently grown increasingly popular, and has been adopted for programming languages such as JavaScript, Cecil, NewtonScript, Io, MOO, REBOL, Kevo, Squeak (when using the Viewer framework to manipulate Morphic components), and several others.2

    JavaScript面向对象编程

    Core Objects

    JavaScript has several objects included in its core; for example, there are objects like Math, Object, Array, and String. The example below shows how to use the Math object to get a random number by using its random() method.

    alert(Math.random());
    
    Note: This and all further examples presume a function named alert (such as the one included in web browsers) is defined globally. The alert function is not actually a part of JavaScript itself.

    See Core JavaScript 1.5 Reference:Global Objects for a list of the core objects in JavaScript.

    Every object in JavaScript is an instance of the object Object and therefore inherits all its properties and methods.

    自定义的类

    JavaScript是一种基于原型的语言,因此并不包含类的声明,而C++或Java中则包含类的声明。有时候,这一点会让熟悉有类的声明的语言的程序员感到困惑。实际上,JavaScript使用方法作为类。定义一个类与定义一个方法一样简单。在下面的例子里,我们定义了一个名为Person的新类。

    function Person() { }
    

    对象(类的实例)

    To create a new instance of an object obj we use the statement new obj, assigning the result (which is of type obj) to a variable to access it later.

    In the example below we define a class named Person and we create two instances (person1 and person2).

    function Person() { }
    var person1 = new Person();
    var person2 = new Person();
    
    Please also see Object.create for a new and alternative instantiation method.

    构造函数

    构造函数将在初始化时调用(当对象实例创建的时刻)。构造函数是类的一个方法。在JavaScript中, the function serves as the constructor of the object; therefore, there is no need to explicitly define a constructor method. Every action declared in the class gets executed at the time of instantiation.

    The constructor is used to set the object's properties or to call methods to prepare the object for use. Adding class methods and their definitions occurs using a different syntax described later in this article.

    In the example below, the constructor of the class Person displays an alert when a Person is instantiated.

    function Person() {
      alert('Person instantiated');
    }
    
    var person1 = new Person();
    var person2 = new Person();
    

    属性(对象的特性)

    Properties are variables contained in the class; every instance of the object has those properties. Properties should be set in the prototype property of the class (function) so that inheritance works correctly.

    Working with properties from within the class is done by the keyword this, which refers to the current object. Accessing (reading or writing) a property outside of the class is done with the syntax: InstanceName.Property; this is the same syntax used by C++, Java, and a number of other languages. (Inside the class the syntax this.Property is used to get or set the property's value.)

    In the example below we define the gender property for the Person class and we define it at instantiation.

    function Person(gender) {
      this.gender = gender;
      alert('Person instantiated');
    }
    
    var person1 = new Person('Male');
    var person2 = new Person('Female');
    
    //display the person1 gender
    alert('person1 is a ' + person1.gender); // person1 is a Male
    

    方法

    Methods follow the same logic as properties; the difference is that they are functions and they are defined as functions. Calling a method is similar to accessing a property, but you add () at the end of the method name, possibly with arguments. To define a method, assign a function to a named property of the class's prototype property; the name that the function is assigned to is the name that the method is called by on the object.

    In the example below we define and use the method sayHello() for the Person class.

    function Person(gender) {
      this.gender = gender;
      alert('Person instantiated');
    }
    
    Person.prototype.sayHello = function()
    {
      alert ('hello');
    };
    
    var person1 = new Person('Male');
    var person2 = new Person('Female');
    
    // call the Person sayHello method.
    person1.sayHello(); // hello
    

    In JavaScript methods are regular function objects that are bound to a class/object as a property which means they can be invoked "out of the context". Consider the following example code:

    function Person(gender) {
      this.gender = gender;
    }
    
    Person.prototype.sayGender = function()
    {
      alert(this.gender);
    };
    
    var person1 = new Person('Male');
    var genderTeller = person1.sayGender;
    
    person1.sayGender(); // alerts 'Male'
    genderTeller(); // alerts undefined
    alert(genderTeller === person1.sayGender); // alerts true
    alert(genderTeller === Person.prototype.sayGender); // alerts true
    

    This example demonstrates many concepts at once. It shows that there are no "per-object methods" in JavaScript since all references to the method point to the exact same function, the one we have defined in the first place on the prototype. JavaScript "binds" the current "object context" to the special "this" variable when a function is invoked as a method(or property to be exact) of an object. This is equal to calling the function object's "call" method as follows:

    genderTeller.call(person1); //alerts 'Male'
    
    See more about this on Function.call and Function.apply

    继承

    Inheritance is a way to create a class as a specialized version of one or more classes (JavaScript only supports single class inheritance). The specialized class is commonly called the child, and the other class is commonly called the parent. In JavaScript you do this by assigning an instance of the parent class to the child class, and then specializing it. In modern browsers you can also use Object.create to implement inheritance.

    JavaScript并不探测子类的 prototype.constructor 请参阅Core JavaScript 1.5 Reference:Global Objects:Object:prototype属性,所以我们必须人工声明。

    在下面的例子中,我们将定义类Student作为类Person的子类。然后我们将重新定义sayHello()方法,并添加sayGoodBye()方法。

    // define the Person Class
    function Person() {}
    
    Person.prototype.walk = function(){
      alert ('I am walking!');
    };
    Person.prototype.sayHello = function(){
      alert ('hello');
    };
    
    // define the Student class
    function Student() {
      // Call the parent constructor
      Person.call(this);
    }
    
    // inherit Person
    Student.prototype = new Person();
    
    // correct the constructor pointer because it points to Person
    Student.prototype.constructor = Student;
     
    // replace the sayHello method
    Student.prototype.sayHello = function(){
      alert('hi, I am a student');
    }
    
    // add sayGoodBye method
    Student.prototype.sayGoodBye = function(){
      alert('goodBye');
    }
    
    var student1 = new Student();
    student1.sayHello();
    student1.walk();
    student1.sayGoodBye();
    
    // check inheritance
    alert(student1 instanceof Person); // true 
    alert(student1 instanceof Student); // true
    

    Using Object.create the inheritance line would instead be:

    Student.prototype = Object.create(Person.prototype);

    封装

    In the previous example, Student does not need to know how the Person class's walk() method is implemented, but still can use that method; the Student class doesn't need to explicitly define that method unless we want to change it. This is called encapsulation, by which every class inherits the methods of its parent and only needs to define things it wishes to change.

    抽象

    Abstraction is a mechanism that permits modeling the current part of the working problem. This can be achieved by inheritance (specialization), or composition. JavaScript achieves specialization by inheritance, and composition by letting instances of classes be the values of attributes of other objects.

    The JavaScript Function class inherits from the Object class (this demonstrates specialization of the model). and the Function.prototype property is an instance of Object (this demonstrates composition)

    var foo = function(){};
    alert( 'foo is a Function: ' + (foo instanceof Function) );
    alert( 'foo.prototype is an Object: ' + (foo.prototype instanceof Object) );
    

    多态

    Just like all methods and properties are defined inside the prototype property, different classes can define methods with the same name; methods are scoped to the class in which they're defined. This is only true when the two classes do not hold a parent-child relation (when one does not inherit from the other in a chain of inheritance).

    注意事项

    The techniques presented in this article to implement object-oriented programming are not the only ones that can be used in JavaScript, which is very flexible in terms of how object-oriented programming can be performed.

    Similarly, the techniques shown here do not use any language hacks, nor do they mimic other languages' object theory implementations.

    There are other techniques that make even more advanced object-oriented programming in JavaScript, but those are beyond the scope of this introductory article.

    参考文献

    1. Mozilla. "Core JavaScript 1.5 Guide", http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide
    2. Wikipedia. "Object-oriented programming", http://en.wikipedia.org/wiki/Object-...ed_programming

    Original Document Information

    • Author(s): Fernando Trasviña <f_trasvina at hotmail dot com>
    • Copyright Information: © 1998-2005 by individual mozilla.org contributors; content available under a Creative Commons license

    Es: https://developer.mozilla.org/es/docs/Introducción_a_JavaScript_orientado_a_objetos 

    文档标签和贡献者

    对本页有贡献的人: yimity, shiyutang, xcffl, teoli
    最后编辑者: teoli,