"Reprint" JavaScript prototype Inheritance-Learning notes

Source: Internet
Author: User
Tags shallow copy jquery library hasownproperty

Nanyi This article is very well written.

Http://www.ruanyifeng.com/blog/2011/06/designing_ideas_of_inheritance_mechanism_in_javascript.html

The notes are as follows:

It has been difficult to understand the inheritance mechanism of JavaScript language. It does not have the concept of "subclass" and "parent class", and there is nodistinction between "class" and "instance" (instance), and it relies on a very peculiar "prototype chain" (prototype chain) pattern to implement inheritance.
Reading the French programmer Vjeux's explanation, it dawned, fully understand why JavaScript design.

First, from the ancient times.

All the data types in JavaScript are objects (object), which is very similar to Java. However, he immediately encountered a problem, in the end should not design "inheritance" mechanism?

Second, the choice of Brendan Eich

Brendan Eich finally designed the "inheritance". However, he does not intend to introduce the conceptof "class", because once the "class" is available,JavaScript is a complete object-oriented programming language,
It seems to be a bit too formal, and adds beginner's entry difficulty. C+ + and Java invoke the constructor of the class (constructor) when using the new command. He made a simplified design, in the JavaScript language, the new command was followed by a class,
Instead, it is a constructor function.  For example, there is now a constructor called Dog that represents the prototype of a canine object. function DOG (name) { this. Name =new Dog (' da Mao'// woolen

Iii. disadvantages of the new operator

One disadvantage of generating instance objects with constructors is that you cannot share properties and methods. Each instance object has its own copy of the properties and methods. This not only can not do data sharing, but also a huge waste of resources.

Iv. Introduction of prototype attributes

Brendan Eich decides to set a prototype property for the constructor.

This property contains an object (hereinafter referred to as the "prototype object"), where all instance objects need to share properties and methods that are placed inside the object, and those that do not need to be shared are placed inside the constructor.

Once the instance object is created, the properties and methods of the prototype object are automatically referenced. In other words, the properties and methods of an instance object are divided into two types, one local and the other referenced.

The attribute is placed in the prototype object and is shared by two instance objects. As long as the prototype object is modified, it affects two instance objects at the same time.

V. Summary

Since all instance objects share the same prototype object, it appears from the outside that the prototype object is like a prototype of an instance object, and the instance object is like "inheriting" the prototype object.

This is the design idea of the JavaScript inheritance mechanism. The following three articles describe the specific application of the inheritance mechanism:

* JavaScript Object-oriented programming (i): encapsulation

* JavaScript Object-oriented Programming (II): Inheritance of constructors

* JavaScript Object-oriented Programming (III): Inheritance of non-constructors

The notes are as follows:

I. Encapsulation

To solve the problem of generating instances from prototype objects, JavaScript provides a constructor (Constructor) pattern.

The so-called "constructor", in fact, is a normal function, but the internal use of this variables.

Using an operator on a constructor new enables you to generate an instance, and the this variable is bound to the instance object.

function Cat (name,color) {  this. name=name;  this. color=new Cat ("Da Mao", "Yellow"new Cat ("Er Mao", "Black  " // Mao // Yellow

JavaScript also provides an instanceof operator that validates the relationship between a prototype object and an instance object.

instanceof // true instanceof // true

Problem with constructor mode

The constructor method works well, but there is a problem of wasting memory. That is, for each instance object, the type properties and methods are exactly eat() the same, and each time an instance is generated, it must be a duplicate of the content and occupy more memory. This is neither environmentally friendly nor inefficient.

Prototype mode

JavaScript specifies that each constructor has a prototype property that points to another object. All properties and methods of this object are inherited by an instance of the constructor.

This means that we can define the invariant properties and methods directly prototype on the object.

At this point, all instances of the type properties and methods, in fact, are the eat() same memory address, pointing prototype to the object, thus improving the efficiency of the operation.

function Cat (name,color) {  this. Name = name;  this. color == "Feline"= function () {alert ("Eat Mouse")};

There is another way to do this:

function Dog (name) {  this. Name == {species: ' canine 'new Dog (' Mao '
   
    new Dog (' Er Mao '
    
    / 
      /Canine/ 
    / 
     Canine Division
   

Verification method of prototype mode

To match prototype the attributes, JavaScript defines some helper methods that help us to use it.

isPrototypeOf ()

This method is used to determine the proptotype relationship between an object and an instance.

Alert (Cat.prototype.isPrototypeOf (CAT1)); True

hasOwnProperty ()

Each instance object has a hasOwnProperty() method that is used to determine whether a property is a local property or a property inherited from an prototype object.

Alert (Cat1.hasownproperty ("name")); True

Alert (Cat1.hasownproperty ("type")); False

In operator

inThe operator can be used to determine whether an instance contains a property, whether it is a local property or not.

Alert ("name" in CAT1); True

inOperators can also be used to traverse all properties of an object.

For (Var prop in cat1) {alert ("cat1[" +prop+ "]=" +cat1[prop]);}

Two. Inheritance of constructors

Here are five ways to "inherit" between objects.

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 =new 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.

Cat.prototype =NewAnimal (); Cat.prototype.constructor=Cat; var cat1=NewCat ("Da Mao", "Yellow"); alert (cat1.species); //Animalin the first line of the code, we point the cat's prototype object to an instance of animal. Cat.prototype=NewAnimal (); 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? Cat.prototype.constructor=Cat; Originally, any prototype object has a constructor property that points to its constructor. If not"Cat.prototype = new Animal ();"this line,
Cat.prototype.constructor is pointing to Cat; After adding this line, Cat.prototype.constructor points to animal. Alert (Cat.prototype.constructor= = Animal);//trueMore importantly, each instance also has a constructor property, which calls the prototype object's constructor property by default. Alert (Cat1.constructor= = Cat.prototype.constructor);//truetherefore, in the run"Cat.prototype = new Animal ();"after this line, Cat1.constructor also points to animal! Alert (Cat1.constructor= = Animal);//trueThis 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 the prototype object is replaced, the O.prototype={}; Then the next step must be to add the constructor property to the new prototype object and refer to this property back to the original constructor. O.prototype.constructor= O;

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.

= "Animal"==new 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  =//  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 F ==new= Cat;
// Animal

Encapsulated as a function:

==new==new Cat ("Da Mao", "Yellow"// Animal This extend function, is how Yui Library implements the method of inheriting . 

In addition, it is stated 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

Can change a way of thinking, purely using the "copy" method to achieve inheritance.

Write a function that implements the purpose of the property copy.

== child.prototype;   for== p; }

When used, write this:

New Cat ("Da Mao", "Yellow"//  animal

Three. Inheritance of non-constructor functions

The first part of this series describes "encapsulation", and the second section describes using constructors to implement "inheritance."

First, what is the "non-constructor" inheritance?

For example, there is now an object called "Chinese" = {nation:' China ' }; There is also an object called "Doctor" ={career:' Doctor ' } How can I let "Doctor" to Inherit "Chinese", that is, how can I generate a "Chinese doctor" object?

It is important to note that both objects are ordinary objects, not constructors, and cannot be implemented using constructor methods for "inheritance."

Second, the object () method

An object () function that can do this.

= o;  returnnew== ' Doctor '// China

Three, shallow copy

In addition to using the "prototype chain", there is another way of thinking: The Parent object's properties, all copied to the child object, can also implement inheritance.

= {};     for== p;  return== ' Doctor '//  China

However, there is a problem with such a copy. That is, if the parent object's property is equal to an array or another object, then actually the child object obtains only one memory address, not a real copy, so there is a possibility that the parent object will be tampered with.

Four, deep copy

The so-called "deep copy" is the ability to make real-world copies of arrays and objects. Its implementation is not difficult, as long as the recursive call "shallow copy" on the line.

= C | |     {};   for (var i in P) {  if (typeof p[i] = = = 'object ' = (P[i].constructor = = = = Array ) ?       else= P[i];  }}  return  C; }

Use this to write:

var Doctor == [' Beijing ', ' Shanghai ', ' Hong Kong ']; Doctor.birthPlaces.push (' Xiamen '); At this point, the parent object will not be affected.

alert (doctor.birthplaces); BEIJING, Shanghai, Hong Kong, Xiamen

alert (chinese.birthplaces); BEIJING, Shanghai, Hong Kong

Currently, thejquery library is using this method of inheritance .

Finish

"Reprint" JavaScript prototype Inheritance-Learning notes

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.