How to inherit from 6 in JavaScript

Source: Internet
Author: User
Tags shallow copy

1. Prototype chain inheritance

Let's review the relationship of constructors, prototypes, and instances: each constructor has a prototype object, and the prototype object contains a pointer to the constructor, and the instance contains a point to the prototype object

The internal pointer. If we make the prototype object equal to another instance of the type, a prototype chain is formed.

    functionsupertype () { This. Name = ' Supertype '} SuperType.prototype.sayNmae=function() {Console.log ( This. Name)} functionsubtype () { This. Remark = ' subtype '} subtype.prototype=Newsupertype () SubType.prototype.sayRemark=function() {Console.log ( This. Remark)} varInstance1 =Newsubtype () Console.log (Instance1instanceofSubtype)//trueConsole.log (Instance1instanceofsupertype)//trueConsole.log (Instance1instanceofObject)//true

No more than a picture to understand that along the __proto__ is what we call the prototype chain. In addition, the superclass refers to the supertype, and the subtype refers to the subtype

Problems with the prototype chain

    functionsupertype () { This. colors = [' red ', ' yellow ', ' blue ']    }    functionsubtype () {} Subtype.prototype=Newsupertype ()varInstance1 =Newsubtype ()varInstance2 =Newsubtype () Instance1.colors.push (' Green ') Console.log (instance1.colors)//["Red", "yellow", "blue", "green"]Console.log (instance2.colors)//["Red", "yellow", "blue", "green"]

A prototype property that contains a reference type value is shared by all instances where the colors defined in the superclass are originally owned by each instance, but because the supertype instance is the prototype of the subtype,

Colors is also shared by all subtype instances, so modifying one instance colors and other instances will change

Another problem with the prototype chain is that when you create a self-type instance, you cannot pass a value to a super-type constructor

2. Borrowing constructors

    functionsupertype (name) { This. Name =name This. colors = [' Red ', ' blue ', ' green ']    }    functionsubtype () {supertype.apply ( This, arguments)//calling a hyper-type inside a subtype    }    varInstance1 =NewSubtype (' Alan ')    varInstance2 =NewSubtype (' Bob ')) Instance1.colors.push (' Black ') Console.log (instance1.colors)//["Red", "Blue", "green", "black"]Console.log (instance2.colors)//["Red", "Blue", "green"]Console.log (Instance1.name)//AlanConsole.log (Instance2.name)//Bob

The most important step in borrowing a constructor is to call the super-type constructor inside the subtype, modify this point, and satisfy the pass of the parameter

Problems with borrowing constructors

Methods are defined in constructors and cannot implement function reuse

3. Combining inheritance

Combinatorial inheritance, also known as Classic inheritance, solves the problem of prototype chains and borrowing constructors.

 

    functionsupertype (name,age) { This. Name =name This. Age = Age This. colors = [' Red ', ' blue ', ' green ']} object.defineproperties (supertype.prototype,{sayname:{value:function() {Console.log ( This. Name)}, writable:true, Configurable:true, Enumerable:true        }    })    functionsubtype () {supertype.apply ( This, arguments)//second call to the super-type constructor} Subtype.prototype=Newsupertype ()//First call to a superclass constructorvarInstance1 =NewSubtype (' Banks ', 22)    varInstance2 =NewSubtype (' Bob ', 33) Instance1.colors.push (' Black ') Console.log (instance1.colors)//["Red", "Blue", "green", "black"]Console.log (instance2.colors)//["Red", "Blue", "green"]

Combine inheritance, define non-public properties in constructors, and define common methods in the prototype.

Problems with combinatorial inheritance

If there is a problem with this inheritance, it is called the two-time super-type constructor.

4. prototype-Type Inheritance

Douglas, Gram Rockford (yes, the small partner who proposed the safe object) proposed a prototype inheritance. His idea is to create new objects with existing objects without having to create custom types.

function Object (o) {        function F () {   // corresponds to the self-type constructor in the prototype chain inheritance         }        = O   //  the O here is equivalent to an instance        of a superclass in the prototype chain inheritance return New F ()    }

Inside the object () function, a temporary constructor is created, then the incoming object is used as a prototype of the constructor, and a new instance of the temporary type is returned.

There are similarities to prototype chain inheritance, but there is no super-type constructor, and a series of operations are encapsulated inside the object function. In essence, Object ()

A sneak copy was performed.

    varperson ={name:' Nicholas ', Age:22, friends:[' Shelby ', ' Court ', ' Van ']    }    varAnotherperson =object (person) Anotherperson.name= ' Alan 'AnotherPerson.friends.push (' Bob ')    varYetanoterperson =object (person) console.log (anotherperson.name)//AlanConsole.log (Anotherperson.friends)//[' Shelby ', ' Court ', ' Van ', ' Bob ']Console.log (Yetanoterperson.name)//NicholasConsole.log (Yetanoterperson.friends)//[' Shelby ', ' Court ', ' Van ', ' Bob ']

Prototype inheritance to have one object as an inheritance of another object, then pass the object to the object function and modify the resulting object as required

But the person object contains the Friends reference type, here the Friends is common, here in the modification (note is modified, not changed)

    Anotherperson.friends = [' Shelby ']    console.log (anotherperson.friends)      //["Shelby"]     Console.log (yetanoterperson.friends)    //[' Shelby ', ' Court ', ' Van ', ' Bob ']

The above code we changed the Anotherperson friends, here will add a Friends attribute in the Anotherperson instance, and will not change, the person's friends

The same is true of the prototype chain inheritance.

The problem of prototype inheritance

Primitive inheritance creates objects that are equivalent to copies of incoming objects, and as with the problem of the prototype chain inheritance, each instance has no custom properties. And prototype inheritance is a shallow copy and cannot be detected with the instanceof operator.

About instanceof operator and prototype chain reference this article

Https://www.cnblogs.com/flawlessBlithe/p/8515435.html

5. Parasitic inheritance

The idea of parasitic inheritance is similar to a parasitic constructor and a factory pattern, which is to create a function that encapsulates the inheritance process, which internally enhances the object in some way, and then returns the object.

function Createanother (original) {        var clone = Object (original)        function () {     Add a method to an instance console.log (' Hi ')}                     return before//in some way to enhance an object to return an instance  clone    }

Problems with parasitic inheritance

Parasitic inheritance solves the problem of unable to customize the method of prototype inheritance, but it is still a shallow copy and cannot be detected by instanceof operator.

6. Parasitic combined inheritance

Look at the name everyone thought, parasitic composite inheritance is to solve, parasitic inheritance can not be instanceof operator detection problems, and combined inheritance calls two super-type constructors.

functionObject (o) {functionF () {//equivalent to a subtype constructor in a prototype chain inheritance} f.prototype= O//the o here is equivalent to an instance of a super type in the prototype chain inheritance    return NewF ()}functionsupertype (name,age) { This. Name =name This. Age =Age } SuperType.prototype.sayName=function() {Console.log ( This. Name)}functionsubtype () {supertype.apply ( This, arguments)}//The following function is done to solve the problem of the second call to the superclass constructor in composite inheritance//This step subtype.prototype = new Supertype ()functionInheritprototype (subtype,supertype) {varN = Object (Supertype.prototype)//shallow copy of a super-type prototypeN.constructor = Subtype//If you do not follow this step, you will not be able to use instanceof to check for instances of subtype    /*the above operation is to create a copy of the Supertype.prototype using the prototype inheritance method, which is replacing the new supertype () step*/Console.log (n.__proto__= = = Supertype.prototype)//trueConsole.log (ninstanceofsupertype)//trueSubtype.prototype =N}inheritprototype (subtype,supertype) SubType.prototype.sayAge=function() {//The addition of the Sayage method in prototype is already added to the N on the inside of the Inheritprototype function .Console.log ( This. Age)}varInstance =NewSubtype (' Alan ', 23) Console.log (instanceinstanceofSubtype)//trueConsole.log (instanceinstanceofsupertype)//true

Parasitic combined inheritance is more difficult to understand where the second call to the super-type constructor should be resolved.

I heard that parasitic composite inheritance is still a problem ..... It should be too much trouble, hahaha.

How to inherit from 6 in JavaScript

Related Article

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.