JavaScript inheritance in detail (i)

Source: Internet
Author: User

object-oriented and object-based

Almost every developer has a development experience with object-oriented languages such as C + +, C #, and Java. In the traditional object-oriented language, there are two very important concepts-classes and instances. A class defines the behavior and methods of a class of things, whereas an instance is a concrete implementation of classes. We also know that object-oriented programming has three important concepts-encapsulation, inheritance, and polymorphism.

But in the world of JavaScript, all of this doesn't seem to exist. Because JavaScript itself is not an object-oriented language, it is an object-based language. There are some interesting features here, such as that everything in JavaScript is an object, including strings, arrays, dates, numbers, and even functions, such as the following example:

    Define a function-add    function Add (A, b) {        add.invoketimes++;        return a + B;    }    Because the function itself is also an object, here is an attribute for the function add to record the number of times this function was called    add.invoketimes = 0;    Add (1 + 1);    Add (2 + 3);    Console.log (Add.invoketimes); 2    

simulating classes and inheritance in JavaScript

In object-oriented languages, we use classes to create a custom object. While everything in JavaScript is an object, what is the way to create a custom object?

This requires the introduction of another concept-prototype (prototype), we can simply think of prototype as a template, the newly created custom object is a copy of the template (prototype) (actually not a copy but a link, but the link is not visible, It feels like a copy to the people.

Let's take a look at an example of creating a custom object through prototype:

constructor function person    (name, sex) {        this.name = name;        This.sex = sex;    }    Define the prototype of the person, the properties in the prototype can be referenced by custom object    Person.prototype = {        getname:function () {            return this.name;        },        Getsex:function () {            return this.sex;        }    }    

Here we refer to the function person as the constructor, which is the function that creates the custom object. As you can see, JavaScript simulates the functionality of a class by constructing functions and prototypes.
Code to create a custom object (instantiation Class):

     var Zhang = new person ("Zhangsan", "man");    Console.log (Zhang.getname ()); "Zhangsan"    var chun = new Person ("Chunhua", "Woman");    Console.log (Chun.getname ()); "Chunhua"    

When code var Zhang = new person ("Zhangsan", "man") executes, there are actually several things that are done internally:

    • Creates a blank object (new Object ()).
    • Copy the attributes in Person.prototype (key-value pairs) into this empty object (as we mentioned earlier, the internal implementation is not a copy but a hidden link).
    • Pass the object through the This keyword to the constructor and execute the constructor.
    • Assign this object to the variable Zhang.

To prove that the prototype template is not copied to the instantiated object, but rather a link, see the following code:

     function person (name, sex) {        this.name = name;        This.sex = sex;    }    Person.prototype.age =;    var Zhang = new person ("Zhangsan", "man");    Console.log (Zhang.age);    //Overwrite The age attribute in prototype    zhang.age = +;    Console.log (Zhang.age);    Delete zhang.age;    After the instance attribute age is removed, this property value is also obtained from prototype    Console.log (zhang.age);//20    

This hidden prototype link, implemented within JavaScript, is the moist soil that JavaScript relies on to survive, and is the basis for the simulation of inheritance.

How do I implement simple inheritance in JavaScript?
The following example creates an employee class employee, which inherits all the properties from the prototype prototype from person.

     function Employee (name, sex, EmployeeID) {        this.name = name;        This.sex = sex;        This.employeeid = EmployeeID;    }    To point the employee's prototype to an instance of person    //Because an instance of person can invoke a method in the person prototype, an instance of an employee can also invoke all the attributes in the person prototype.    employee.prototype = new Person ();    Employee.prototype.getEmployeeID = function () {        return this.employeeid;    };    var Zhang = new Employee ("Zhangsan", "Man", "1234");    Console.log (Zhang.getname ()); "Zhangsan    

The above implementation of inheritance is coarse, and there are many problems:

    • It is not appropriate to instantiate a person when creating an employee constructor and prototype (hereafter referred to as a class).
    • The constructor of the employee cannot invoke the constructor of the parent class person, resulting in a duplicate assignment of the name and sex attributes in the employee constructor.
    • The function in the employee overrides the function with the same name in person, without overloading the mechanism (and the previous one is a type of problem).
    • The syntax for creating JavaScript classes is too fragmented to be as elegant as the syntax in C#/java.
    • The implementation has a pointing error in the constructor attribute, which is discussed in the second article.

We will refine this example in Chapter three.

implementation of JavaScript inheritance

Because JavaScript itself does not have complete classes and inherited implementations, and we also see a lot of problems with manual implementations, there are many implementations of this challenging task online:

    • Douglas Crockford-prototypal Inheritance in JavaScript
    • Douglas crockford-classical Inheritance in JavaScript
    • John resig-simple JavaScript Inheritance
    • Dean edwards-a Base Class for JavaScript inheritance
    • Prototype
    • Mootools
    • ExtJS

This series of articles will analyze each of these implementations in depth, culminating in an in-depth understanding of how classes and inheritance can be implemented in JavaScript.

In the next chapter we will introduce the relevant knowledge in class implementation, such as this, constructor, prototype and so on.




JavaScript inheritance in detail (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.