The Inheritance in JS

Source: Internet
Author: User

Two types of inheritance are supported in object-oriented languages: interface inheritance and implementation inheritance, but because the function in JS is not signed (the type and number of parameters received are different), interface inheritance cannot be implemented.

Here's how to implement inheritance in JS:

First, the prototype inheritance

Prototype inheritance: Inherits both the template of the parent class and the prototype object of the parent class.

functionPerson (name,age) { This. name=name;  This. age=Age ;} Person.prototype.sayName=function() {alert ( This. name);}functionBoy () {}boy.prototype=NewPerson (' a ', 12); Boy.prototype.sayHello=function() {alert (' Hello ');}varboy=NewBoy (); alert (boy.name);//aBoy.sayname ();//aalert (boy.constructor);//function Person (...) {...}Alert (Boyinstanceofperson);//trueAlert (BoyinstanceofBoy);//true

From the above, the constructor of the subclass instance points to the constructor of the parent class (Boy.prototype points to another prototype, and the constructor of the prototype is the parent class). The subclass instance is also the person class and the boy class. However, there is a problem: if you need to pass a parameter in the constructor, you must upload the parameter in the new person (), and if you pass the argument in the Create subclass instance, the undefined will be displayed as follows:

functionPerson (name,age) { This. name=name;  This. age=Age ;} Person.prototype.sayName=function() {alert ( This. name);}functionBoy () {}boy.prototype=NewPerson (); Boy.prototype.sayHello=function() {alert (' Hello ');}varboy=NewBoy (' a ', 12); alert (boy.name);//undefined

Although it inherits both the template of the parent class and the prototype object of the parent class, it is masked if parameters are passed in subclasses.

Schematic of the prototype inheritance:

Constructors. Prototype= Prototypes

Prototypes. constructor= Constructors

The internal pointer in the instance points to the prototype

function Person () {}person.prototype.setname=function() {}; var person=New person (); function Boy () {}boy.prototype=person; var boy=new Boy ();

Search steps for Inheriting call methods: ① Search Instance ② search subclass. Prototype③ Search Parent class. prototype

Second, the way to inherit the constructor function

This inheritance inherits only the template and does not inherit the prototype object, which causes the function to be reused.

function Person (name,age) {  this. name=name;    this. age= age;} function Boy (name,age) {    Person.call (This, ' a ');   inherits the template  of the parent class var boy=new boy (); alert (boy.name); // a
Iii. combination Inheritance (most commonly used inheritance mode)

Combining inheritance is the combination of prototype inheritance and borrowing constructors.

functionPerson (name,age) { This. name=name;  This. age=Age ;} Person.prototype.sayName=function() {alert ( This. name);}functionBoy (name,age,sex) { This. sex=sex; Person.call ( This, name,age);} Boy.prototype=NewPerson (); Boy.prototype.sayHello=function() {alert (' Hello ');}varboy=NewBoy (' A ', 12, ' man ')); alert (boy.name);//aalert (boy.sex);//maleBoy.sayname ();//aBoy.sayhello ();//Hello
However, this inheritance inherits from the template of the parent class once Person.call (), and boy.prototype=new person (), inheriting a prototype object and inheriting the template once again. This results in a template that inherits two times from the parent class. So can we just assign the parent prototype to the subclass prototype?
functionPerson (name,age) { This. name=name;  This. age=Age ;} Person.prototype.sayName=function() {alert ( This. name);}functionBoy (name,age,sex) { This. sex=sex;} Boy.prototype.sayHello=function() {alert (' Hello ');} Boy.prototype=NewPerson ();varboy=NewBoy (' A ', 12, ' man ')); alert (boy.name);//aalert (boy.sex);//malealert (boy.constructor); Boy.sayname ();//aBoy.sayhello ();//Error

No, because if the parent prototype is assigned directly to the subclass prototype, the method defined in the call to the subclass prototype will give an error: Uncaught TypeError:boy.sayHello is not a function. So how do we solve this problem?

We can define ourselves a method that inherits only the parent class prototype object:

functionExtend (sub,sup) {functionF () {};//Create an empty constructorF.prototype=sup.prototype;//to assign the prototype of the parent class to the prototype of an empty constructorSub.prototype=NewF (); Sub.prototype.constructor=sub;//also the constructor of the atomic classSub.superclass=sup.prototype;//Save the prototype object of the parent class    if(sub.prototype.constructor==Object.prototype.constructor) {Sub.prototype.constructor=sub;//prevents a subclass's constructor from being an object    }    }functionPerson (name,age) { This. name=name;  This. age=Age ;} Person.prototype.sayName=function() {alert ( This. name);}functionBoy (name,age,sex) { This. sex=sex; Boy.superClass.constructor.call ( This, name,age);//The previously saved prototype object is here to act as a decoupling.}extend (Boy,person); Boy.prototype.sayHello=function() {alert (' Hello ');}varboy=NewBoy (' A ', 12, ' man ')); alert (boy.name);//aalert (boy.sex);//maleBoy.sayname ();//aBoy.sayhello ();//Hello

This will inherit only one parent class template and one prototype object at a time. The above judgment constructor is intended to be a new object created as an object literal on the following prototype object, and the constructor property of the prototype object becomes the new constructor property, no longer points to the original constructor, but instead points to object.

The above method is called parasitic combined inheritance. He combines archetypal inheritance with parasitic inheritance, which is the most ideal way to inherit a reference type.

So what is prototype inheritance and what is parasitic inheritance?

Iv.. prototype-Type Inheritance

Create an empty constructor within a function, prototype the passed-in object as an empty constructor, and return an instance of the empty constructor. This inheritance must have an object as the basis for another object.

function Object (obj) {    function  F () {};    F.prototype=obj;     return New F ();} var person={    name:' A ', age    :+}; var person2=Object (person); alert (person.name); // aalert (person2.name); // a

This inheritance applies to only one object that you want to keep similar to another object.

A new Object.create (object that is used as a new object prototype, a method for defining additional properties for new objects) is added to ECMA5, which is similar to what we define as Object ().

Supported Browsers: IE + +, Firefox 4+, Safari 5+, Opera 12+, Chrome.

V. Parasitic inheritance

The object is internally enhanced in some way, and then returned.

functionObject (obj) {functionF () {}; F.prototype=obj; return NewF ();}functionCreateanother (SUP) {varo=object (SUP); O.sayhello=function() {alert (' Hello ');    }; returno; }varperson={name:A, Age:12    };varPerson2=Createanother (person);p Erson2.sayhello ();//Hello

This inheritance method applies to objects that are not custom types and constructors.

The Inheritance in JS

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.