The inheritance of JavaScript objects

Source: Internet
Author: User

Inheritance is a very important part of object-oriented language. Many of the OOP languages support interface inheritance and implementation inheritance in two ways. Interface inheritance: Inheriting method signatures; implementing inheritance: Inheriting the actual method. In ECMAScript, the function is unsigned, so it cannot implement interface inheritance, only support implementation inheritance.

There are about six types of inheritance in JavaScript: Prototype chain inheritance, constructor inheritance, combinatorial inheritance, prototype inheritance, parasitic inheritance, and parasitic combined inheritance. Here is a detailed introduction to six ways of inheriting.

1. Prototype chain

The basic idea is to use a prototype to let one reference type inherit the properties and methods of another reference type. Here you have to add that each constructor has a prototype object that contains a pointer to the constructor, and the instance contains an internal pointer to the prototype object.

function Basictype () {     this.property=true;     Getbasicvalue = function () {     return this.property;      };} function Newrtype () {     this.subproperty=false;} Newtype.prototype = new Basictype (); var test = new NewType (); alert (Test.getbasicvalue ());   True

As can be known from above, it is essentially rewriting the prototype object, substituting a new instance of the type. In the case of inheritance through the prototype chain, to access an instance property, there are three steps: 1 Search instance, 2 search Newtype.prototype;3 Search Basictype.prototype, the method is found at this time. If a property or method is not found, the person will always go back up to the end to stop. To determine the relationship between an instance and a prototype, you can use the instanceof and isprototypeof () tests, as long as the prototype in the prototype chain is a prototype of a derived instance of the prototype chain. It is also important to note that when you implement inheritance through a prototype chain, you cannot use object literals to create a prototype method, because the prototype chain is rewritten and the prototype chain is truncated.

2 borrowing constructor inheritance

The general idea is to call the super-type constructor inside the subtype constructor.

function Basictype (name) {
This.name=name; this.color=["Red", "Blue", "green"];} function NewType () { Basictype.call (this, "SYF");
this.age=23;} var test = new subtype (); alert (text.name); Syf
alert (text.age); 23

One advantage of this approach to inheritance is that you can pass parameters to a superclass constructor in a subtype constructor, with the disadvantage that function reuse is not possible.

3 Combined inheritance
Combinatorial inheritance is a method that combines the prototype chain and the borrowed constructor inheritance pattern to have both advantages. The idea is to use the prototype chain to implement the inheritance of the prototype properties and methods, by borrowing the constructor to implement the inheritance of the instance attributes.

function Basictype (name) {     this.name=name;     this.colors=["Red", "Blue", "green"];} Basictype.prototype.sayname=function () {     alert (this.name);} function NewType (name,age) {     basictype.call (this,name);     This.age=age;} var test = new NewType ("Syf", "23°c"), Test.colors.push ("Black"); alert (text.colors)  ; "Red,blue,green,black" alert (test.name);   "SYF" alert (test.age);   23

Combined inheritance avoids the defects of the prototype chain and the way of inheriting the constructor function, which integrates their advantages and becomes the most commonly used inheritance way in JS.

4 prototype Inheritance

Prototype chain inheritance and prototype inheritance have only one word difference, but their mechanism is still different. Prototype inheritance is the creation of new objects with the help of existing objects, which means that one object can be used as the basis for another object. The Inheritance method function is expressed as:

function Object (o) {    function F () {}    f.prototype = O;    return new F ();

We can modify it on the basis of O to create a specific object. Intuitively, the most significant difference from the prototype chain inheritance is that the new operator is not used.

5 Parasitic inheritance

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

function Createanother (original) {    var clone = object (original);//Create a new object by calling the function    clone.sayhi=function () {  //In some way to enhance the object        alert ("HI");    };    return clone; Return Object}

Parasitic inheritance is also a useful pattern in situations where objects are primarily considered rather than custom types and constructors. Using parasitic inheritance to add functions to an object, the function reuse rate is low.

6 Parasitic combined inheritance

The above mentioned the combination of inheritance, which is also the most commonly used in JS basic mode. However, because it calls two super-type constructors: one at the time of the creation of the word type, and the other on the inside of the sub-type constructor. That is, my subtype will eventually contain all the instance properties of the superclass, but these properties will be overridden when the subtype constructor is called. The general idea of parasitic combined inheritance is: Inheriting the attribute by borrowing the constructor, inheriting the method through the compositing form of the prototype chain. That is, instead of calling a super-type constructor to specify a prototype for a subtype, we need a copy of the super-type prototype. Essentially, a parasitic inheritance is used to inherit a super-type prototype, and then the result is assigned to the prototype of the sub-type. The basic pattern is as follows:

function Inheritprototype (subtype, supertype) {      var prototype =object (Supertype.prototype);  Create an object, create a copy of the super-type prototype       prototype.constructor = subtype;   Enhanced objects to add the constructor property to the replica created
Subtype.prototype=prototype; Specifies the object that assigns the newly created object to the prototype of the subtype
}

Because parasitic combined inheritance makes up for the disadvantage of combined inheritance, it is also considered by many developers to be the most ideal way to inherit.

The above is JS in the six ways of inheritance, in the programming practice of the specific choice of which way to decide according to the circumstances, the right is the best, and must use a combination of inheritance or parasitic combined inheritance to complete the inheritance.

The inheritance of JavaScript objects

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.