Classic interview question: JS inheritance mode on

Source: Internet
Author: User

JS is not a traditional object-oriented language, so how does he achieve inheritance? Because JS is based on the prototype chain implementation of object-oriented, JS mainly through the prototype chain lookup to achieve inheritance, there are two main types of implementation, divided into the inheritance based on the constructor, as well as the inheritance of the non-constructor function.

Because the length is longer, so the article divides into the upper and lower part, today explains first half.

Now there are two classes that are constructors, one is the animal class

function  Animal () {    this. Species = "Animal "; }

One is the Cat class

function    Cat (name, color) {    this. Name = name;      this. color = color; }

How to make "cat" inherit "animal" characteristics?

First, constructor binding

The first method is also the simplest method, using the call or Apply method to bind the parent object's constructor to a child object, adding a line to the child object constructor:

function    Cat (name, color) {    animal.apply (this, arguments);        this. Name = name;      this. color = color; }  varnew Cat ("Da Mao", "Yellow"//  animal

Second, prototype mode

The second method is more common, using the prototype property.

If the prototype object of "cat" points to an instance of animal, then all instances of "cat" can inherit animal.

New= Cat;  varnew Cat ("Da Mao", "Yellow"//  animal

In the first line of the code, we point the cat's prototype object to an instance of animal.

It is equivalent to completely removing the original value of the prototype object and then assigning a new value. But what does the second line mean?

It turns out that any prototype object has a constructor property that points to its constructor. If there is no "Cat.prototype = new Animal ();" In this line, Cat.prototype.constructor is pointing to Cat, and after adding this line, Cat.prototype.constructor points to animal.

More importantly, each instance also has a constructor property, which calls the prototype object's constructor property by default.

Therefore, in the run "Cat.prototype = new Animal ();" After this line, Cat1.constructor also points to animal!

This obviously leads to an inheritance chain disorder (CAT1 is obviously generated with the constructor cat), so we have to manually correct the constructor value of the Cat.prototype object to Cat. This is the meaning of the second line.

This is an important point to be sure to follow when programming. This is followed by the following, that is, if you replace the prototype object,

The next step, then, must be to add the constructor property to the new prototype object and refer to this property back to the original constructor.

Third, direct succession prototype

The third method is the improvement of the second method. Because of the animal object, the invariant property can be written directly to Animal.prototype. So, we can also let cat () skip Animal () and inherit Animal.prototype directly.

Now, we'll first rewrite the animal object:

function= "Animal";

Then, the cat's prototype object is then pointed to the animal prototype object, which completes the inheritance.

Cat.prototype == Cat;  varnew Cat ("Da Mao", "Yellow"//  animal

The advantage of doing this compared to the previous method is that it is more efficient (without having to execute and establish an instance of animal) and saves memory. The disadvantage is that Cat.prototype and Animal.prototype now point to the same object, so any changes to the Cat.prototype will be reflected in the Animal.prototype.

So, the above piece of code is actually problematic. Take a look at the second line

Cat.prototype.constructor = Cat;

This sentence actually changed the constructor attribute of the Animal.prototype object too!

// Cat

Iv. use of empty objects as intermediaries

Since the "Direct inheritance prototype" has the disadvantages mentioned above, there is a fourth method, using an empty object as the intermediary.

var function  =new= Cat;

F is an empty object, so it hardly accounts for memory. At this point, modifying the cat's prototype object does not affect the animal prototype object.

// Animal

We encapsulate the above method into a function that is easy to use.

function    Extend (Child, Parent) {        varfunction() {};         = parent.prototype;     New    F ();         = Child ;       = parent.prototype; }

When used, the method is as follows

Extend (Cat, Animal);  varnew Cat ("Da Mao", "Yellow"//  animal

This extend function, is how Yui Library implements the method of inheriting.

Also, note that the last line of the function body

Child.uber = Parent.prototype;

It means setting an Uber property for the sub-object, which points directly to the parent object's prototype property. (Uber is a German word that means "up", "up".) This is equivalent to opening a channel on a child object that can call the parent object's method directly. This line is put here, just to achieve the completeness of inheritance, is purely an alternative nature.

V. Copy inheritance

Above is the use of prototype objects, implementation of inheritance. We can also change a way of thinking, purely using the "copy" method to achieve inheritance. Simply put, if you copy all the properties and methods of the parent object into the sub-object, can you also implement inheritance? So we have a fifth method.

First, all the invariant properties of animal are placed on its prototype object.

function= "Animal";

Then, write a function that implements the purpose of the property copy.

function    Extend2 (Child, Parent) {     var p = parent.prototype;        var c = child.prototype;      for      (var in p) {        = P[i];    }      = p; }

This function is to copy the attributes from the parent object's prototype object to the prototype object of the child object. One by one

When used, write this:

Extend2 (Cat, Animal);  varnew Cat ("Da Mao", "Yellow"//  animal

Classic interview question: JS inheritance mode on

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.