Three ways and examples to implement inheritance in JavaScript _javascript tips

Source: Internet
Author: User

Although JavaScript is an object-oriented language, its inheritance mechanism is different from the traditional object-oriented language in the first design, and is based on the prototype inheritance mechanism, but under this mechanism, inheritance still has some different ways of implementation.

Method one: Class-style inheritance

The so-called class-type inheritance is to imitate the traditional object-oriented language inheritance, inheritance and inherited both are "class", the code is as follows:

First define a parent class (or superclass):

function person (name) {
    this.name=name;
  }

  Person.prototype.getname=function () {return
    this.name;
  };

The attribute of the parent class person is defined in the constructor. You can guarantee that the Name property of its subclass does not share this property with it, but instead it belongs to the subclass and mounts the GetName method on the prototype to allow multiple instances of its subclass to share the method body, which saves memory. (for multiple instances, each new instance will guarantee that the GetName method of these instances refers to the same memory space, not the individual space).

Defines an inheritance method extend, as follows:

function Extend (subclass,superclass) {
    var f=function () {};
    F.prototype=superclass.prototype;
    Subclass.prototype=new F ();
    Subclass.prototype.constructor=subclass;

    Subclass.superclass=superclass.prototype;
    if (superclass.prototype.constructor==object.prototype.constructor) {
      superclass.prototype.constructor= Superclass
    }

  }

In this method, you first create a new class of F, let its prototype be the prototype of the parent class, and let the subclass's prototype point to an instance of the class F, which achieves the purpose of inheriting the parent class, and the subclass's prototype is modified so that the constructor attribute of the modified prototype is directed to the subclass. Let it have the constructor and mount a superclass attribute to the subclass, which enables the subclass to call the parent class, thus establishing the relationship between the subclass and the parent class.

Define a subclass author to inherit the parent class person, as follows:

function Author (name,books) {
    Author.superClass.constructor.call (this,name);
    this.book=books;
  }
  Extend (Author,person);
  Author.prototype.getbooks=function () {return
    this.book;
  }

Here, the constructor of the parent class is invoked through its superclass property in the constructor of the subclass, and the call method is used to convert the this point of the method invocation so that the subclass author also owns (inherits) the properties of the parent class, and the subclass has its own property book. Therefore, the parameter books are assigned to the property book in the constructor to achieve the construction purpose. The Extend function inherits the properties and methods on the person prototype of the parent class (actually only inherits the method, because we have just mounted the method on the prototype and the property is defined in the constructor). At the same time, author has its own method of Getbooks, put it on the corresponding prototype, to achieve further expansion of their own purposes on the basis of inheritance.

This way of inheriting is obviously a class-style inheritance similar to the traditional object-oriented language, the advantage is to be accustomed to the traditional object-oriented concept of the programmer is easy to understand, the disadvantage is that the process is cumbersome, memory consumption slightly larger, because the subclass also has its own constructors and prototypes, and the subclass and the parent class properties are completely isolated, Even though they are the same value, they cannot share the same memory.

Method Two: Prototype inheritance

First you define a parent class, which is not intended to be defined by using constructors, but rather by defining an object literally in terms of the object literal, which is the parent class

var person={
   name: ' Default name ',
   getname:function () {return
     this.name
   }

 };

As with the first method, the object has a property name and a method getname.

A clone method is then defined to implement the subclass's inheritance to the parent class, as follows:

function Clone (obj) {
     function F () {}
     f.prototype=obj;
     return new F ();
   }

The Clone method creates a new object, points the object's prototype to the parent class, parameter obj, and returns the object.

The last subclass then inherits the parent class by cloning the function, as follows:

 var author=clone (person);
 author.book=[' JavaScript '];
 Author.showbook=function () {return
 this.book;
 }

This defines a subclass that inherits the parent person by using the clone function, while extending a property book and a method Showbook, where the subclass also owns the property name, but it is the same as the name value of the parent class, so there is no overwrite, and if not, you can use

Author.name= ' new name ', overwriting this property, to get the value of the child class's Name property.

This kind of archetypal inheritance is simpler and more natural than class inheritance, at the same time, if the attributes of a subclass are the same as those of a parent class, and they are not modified, they actually share the same memory space, such as the name attribute above, and the disadvantage is that it is difficult to understand the traditional object-oriented programmer, If the two have to choose, this is certainly a better way.

Since JavaScript implements inheritance in a prototype way, and if the prototype of each object can only point to an instance of a particular class (not to multiple instances), how do you implement multiple inheritance (that is, let a class have methods and properties that have multiple classes at the same time, and do not define these methods and properties themselves internally)?

In the JavaScript design pattern, we give a method of Mixin class:

First, define an additive class to hold some commonly used methods and properties, these methods and properties can be added to any other class by extension, so that the class is added with certain methods and properties of the class, and if a multiple-additive class is defined and added to a class, then the class is indirectly implemented with "multiple inheritance". Based on this idea, it is implemented as follows:

Additive class Definition:

var mixin=function () {};
  mixin.prototype={
    serialize:function () {
      var output=[];
      For (key in this) {
        Output.push (key+ ": +this[key]);
      }
      Return Output.join (', ');
    }
  }

The additive class has a serialize method for traversing itself, outputting its own properties and property values, and returning them as strings, separated by commas.

Defines an extension method that enables a class to be expanded with attributes or methods of the additive class, as follows:

function augment (Receivingclass,givingclass) {
    if (arguments[2]) {for
      (var i= 2,len=arguments.length;i< len;i++) {
        receivingclass.prototype[arguments[i]]=givingclass.prototype[arguments[i]];
      }
    else
    {for
      (methodname in Givingclass.prototype) {
        if (!receivingclass.prototype[methodname)) {
          Receivingclass.prototype[methodname]=givingclass.prototype[methodname];}}}
 

The method defaults to two parameters, and the first parameter is to accept the extended class. The second argument is the additive class (the class used to augment other classes), and other arguments, if more than two parameters, followed by the method or property name, to indicate that the extended class only wants to inherit the specified property or method of the additive class. Otherwise, all properties and methods of the additive class are inherited by default, in which the first if branch is used to inherit the specified property and method, and the Else branch is the default inheritance of all properties and methods. The essence of the method is to extend (add) the attributes and methods on the prototype of the additive class to the prototype of the extended class, so that it has the properties and methods of the additive class.

Finally, multiple inheritance is implemented using an extension method

Augment (author,mixin);
   var author= new author (' JS ', [' JavaScript design Patterns ']);
   Alert (Author.serialize ());

This defines a author class that inherits from the person's parent class, at the same time, with the method and attributes of Mixin, if you like, you can define n-ary classes to augment the class, it can also inherit the attributes and methods of the other additive classes you have defined, so that you realize multiple inheritance, and finally, The results of the author Serialize method are as follows:

You will find that the class has both the person class, the author class, the properties and methods of the Mixin class, where both the person and the mixin properties and methods are derived through "inheritance," which, in fact, implements multiple inheritance.

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.