The inheritance of JavaScript

Source: Internet
Author: User
Tags shallow copy

The main reference is the "JavaScript Advanced Programming (Third Edition)" This book, according to their own understanding, made the following record

Inheritance is the concept of object-oriented (OO) language, and there are two ways of inheriting it: interface inheritance and implementation inheritance. Interface inheritance inherits only the method signature, while implementing inheritance inherits the actual method. Because the function is not signed, interface inheritance cannot be implemented in JavaScript, only implementation inheritance is supported.

Prototype chain inheritance

constructor, prototype, and instance relationships: Each constructor has a prototype object, and the prototype object contains a pointer to the constructor, and the instance contains an internal pointer to the prototype object.

The default prototype for all functions is an instance of object

What if you let the prototype object be equal to another type of instance? Obviously, the prototype object at this point will contain a pointer to another prototype, and the other prototype also contains a pointer to another constructor.

Specific code:

1 function supertype () {2        This. Proterty =true3     }4SuperType.prototype.getSuperValue =function () {5       return  This. Proterty6     }7 function subtype () {8        This. Subproperty =false9     }Ten     //inherited the supertype. OneSubtype.prototype =Newsupertype () ASuperType.prototype.getSubValue =function () { -       return  This. Subproperty -     } the     varInstance =Newsubtype () -Instance.getsupervalue ()//true

Judging the relationship between prototypes and instances

Use instance or isprototypeof

1     Alert (instance instanceof subtype)  //  true2     alert ( SubType.prototype.isPrototypeOf (instance))  //True

Disadvantages:

(i), as long as an instance, constructor, or prototype object modifies a property or method, it affects other object instances on the prototype chain

(b), when an instance of a type is created, there is no way to pass parameters to a super-type constructor without affecting who has an object instance

Borrowing constructors

1 function Subertype () {2        This. colors = ["Red","Blur"]3     }4 function subtype () {5       //inherited the Subertype.6       //using call to change the scope of this, use apply can also7Subertype.call ( This)8     }9     varInstance =Newsubtype ()TenInstance.colors.push ("Black") One alert (instance.colors)//Red,blur,black
 - var New   alert (instalce2.colors)//Red,blur

Pros: You can pass parameters to a super-type constructor in a sub-type constructor

1 function Subertype (name) {2          This. Name =name3       }4 function subtype () {5         //inherited the Subertype and passed the parameters6Subertype.call ( This,"Zhao")7          This. Age =" -"8       }9       varInstance =Newsubtype ()TenAlert (Instance.name)//Zhao OneAlert (instance.age)// -

Disadvantages:

Methods are defined in constructors, and functions cannot be reused. And the method defined in the super-type prototype, the subtype is not visible

Combining inheritance

The technique of prototype chains and constructors is combined together. The idea is to use the prototype chain to implement the inheritance of the prototype properties and methods, and to implement the inheritance of the instance properties by borrowing the constructor function.

1 function Subertype (name) {2        This. Name =name3        This. colors = ["Red","Blue"]4     }5SuberType.prototype.sayName =function () {6Alert This. Name)7     }8 function Subtype (name,age) {9       //Inheritance PropertiesTenSubertype.call ( This, name)//First call Subertype () One        This. Age = Age A     } -     //Inheritance Method -Subtype.prototype =NewSubertype ()//Second call Subertype () theSubType.prototype.sayAge =function () { -Alert This. Age) -     } -     varInstance1 =NewSubtype ("Zhao", -) +Instance1.colors.push ("Black") -Alert (instance1.colors)//Red,blue,black +Instance1.sayname ()//Zhao AInstance1.sayage ()// - at  -     varInstance2 =NewSubtype ("W", -) -Alert (instance2.colors)//Red,blue -Instance2.sayname ()//W -Instance2.sayage ()// -

Pros: Instances have their own attributes, and the same method

Cons: The constructor of a super type is called twice

Prototype inheritance

Prototypes allow you to create new objects based on existing objects without having to customize the type

1    Object (o) {2      function F () {}3         f.prototype = o4          Returnnew  F ()6     }

The essence of the above function is that object () performs a shallow copy of the incoming object

1  varperson = {2Name'Zhao',3Friends: ['Zhao1','Zhao2','Zhao3']4     }5     varAnotherperson =Object(person)6Anotherperson.name ='SS'7AnotherPerson.friends.push ('Bob')8 9     varYetanotherperson =Object(person)TenYetanotherperson.name ='RR' OneYetAnotherPerson.friends.push ('Bar') AAlert (person.friends)//Zhao1,zhao2,zhao3,bob,bar

ECMASCRIPT5 uses the new Object.create () method to standardize the prototype inheritance, which takes two parameters, an object to be used as the prototype of the new object, and (optionally) an object that defines additional properties for the new object

In the case of passing in a parameter, Object.create () is the same as Object ()

1     varperson = {2Name'Zhao',3Friends: ['Zhao1','Zhao2','Zhao3']4     }5     varAnotherperson =object.create (person)6Anotherperson.name ='SS'7AnotherPerson.friends.push ('Bob')8 9     varYetanotherperson =object.create (person)TenYetanotherperson.name ='RR' OneYetAnotherPerson.friends.push ('Bar') AAlert (person.friends)//Zhao1,zhao2,zhao3,bob,bar

The second parameter of Object.create () overrides the property with the same name on the prototype object

1     varperson = {2Name'Zhao',3Friends: ['Zhao1','Zhao2','Zhao3']4     }5     varAnotherperson =object.create (person)6Anotherperson.name ='SS'7AnotherPerson.friends.push ('Bob')8 9     varYetanotherperson =object.create (person)TenYetanotherperson.name ='RR' OneYetAnotherPerson.friends.push ('Bar') AAlert (person.friends)//Zhao1,zhao2,zhao3,bob,bar

The inheritance of 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.