A detailed description of how JavaScript inherits

Source: Internet
Author: User

JavaScript is not an object-oriented language, it is an object-based language. Everything is an object in JavaScript. The way to create custom objects in JavaScript article, I've covered basic methods for creating custom types. So how do you implement the inheritance between type and type? This is what this article is going to say.

JavaScript implements inheritance in two main ways: prototype chain inheritance and constructor inheritance

First, the prototype chain inheritance

The main idea of the prototype chain inheritance is to assign an instance of the parent type to the prototype of the subtype, which can access all the properties and methods of the parent type through [[prototype]] of the prototype object. The specific implementation is as follows:

function supertype () {this.property = true;        Supertype Instance Property Property}supertype.prototype.getsupervalue = function () {return this.property;        Supertype method Getsupervalue ()}function subtype () {this.subproperty = false;    Subtype Instance property Subproperty}; Subtype.prototype = new Supertype ();    The supertype instance is assigned to subtype's prototype SubType.prototype.constructor = subtype; SubType.prototype.getSubValue = function () {return this.subproperty;            Subtype Add Method Getsubvalue ()};var instance = new subtype (); alert (Instance.getsupervalue ());    True

In an instance of the parent type supertype, there is an internal pointer [[prototype]] that points to the prototype of Supertype, and when the instance is assigned to a prototype of a subtype subtype, instance searches for its properties when searching for properties. It then searches the properties of its prototype Subtype.prototype, including the instance properties of Supertype and after adding its own prototype properties, and then continues to search for properties of Supertype.prototype. This allows the subtype to access all the properties of the supertype. That is, the implementation of inheritance. This inheritance is achieved by creating a prototype chain between them.

However, there are some problems with the prototype chain inheritance. First, a subtype cannot pass parameters like a parent type, and second, because the instance properties of the parent type become prototype properties of the subtypes, then the property values of those reference types are shared across all instances of the subtype, often in a different way than we expected.

Second, with the help of the constructor function inheritance

The constructors have their own advantages over the common problem of reference types in the prototype, which is also mentioned in the previous tutorial on creating object methods. The idea of inheriting with constructors is to call the parent class constructor in the subclass constructor. The implementation method is as follows:

function Supertype (name) {this.name = Name;this.friends = ["Mike", "John"];} Function subtype () {//calls the Supertype constructor and passes a parameter for it, setting the subtype name and friends property value Supertype.call (this, "Nicholas"); Add an attribute for subtype age  this.age = "22";} var Instance1 = new subtype (); alert (instance1.name);           Nicholasinstance1.friends.push ("Kate");  alert (instance1.friends);        Mike,john,katealert (instance1.age);            22var Instance2 = new Supertype ("Jake"); alert (instance2.friends);        Mike,johnalert (instance2.name);           Jake

The constructor of Supertype is called through the call () method in the subtype constructor, so that all instances of subtype have a firends copy, and there is no common problem. And you can pass in arguments when you call the Supertype constructor.

Of course, the disadvantage of this method is also obvious, it can not realize the reuse of functions.

Third, the combination of inheritance

Combinatorial inheritance is the most common method of inheritance in JavaScript, which combines the advantages of prototype inheritance and constructor inheritance by inheriting the instance properties of a parent type with a constructor and inheriting the prototype method of the parent type with the prototype chain. Here's how:

function Supertype (name) {///Parent class instance Property THIS.name = Name;this.friends = ["Mike", "John"];} The parent class's prototype method (function) SuperType.prototype.sayName = function () {alert (this.name);};             Function subtype (name,age) {///child class instance properties//Call the parent class's constructor, inherit the parent class's Instance property Name,friends Supertype.call (this, name);                 This.age = age; Subclass the newly added instance property}//assigns the instance of the parent class to the prototype of the subclass, and the prototype chain inherits the parent class's prototype method Sayname () Subtype.prototype = new Supertype (); SubType.prototype.constructor = subtype;//Subclass The newly added method function SubType.prototype.sayAge = function () {alert (this.age);};     var Instance1 = new Subtype ("Nicholas"); Instance1.friends.push ("Kate"); alert (instance1.friends);           Mike,john,kateinstance1.sayage ();          22instance1.sayname ();     Nicholasvar Instance2 = new Subtype ("Jake"); alert (instance2.friends);           Mike,johninstance2.sayage ();          25instance2.sayname (); Jake

In this example, the name and friends properties of the parent class are added to the subclass by calling Supertype's constructor in the subtype constructor. An instance of a parent class is then assigned to a subclass, which implements the connection of the prototype chain, inheriting the Sayname () method of the parent class.

This approach incorporates the advantages of the first two methods and looks perfect, but in fact it has a disadvantage: it invokes the constructor of the parent class two times, so that both the constructor and the prototype of the child class contain the instance properties of the parent class. As the above example, the first call is when the parent class's instance is assigned to the prototype of the subclass, New Supertype (), so that the child class's prototype has an instance property of the parent class. The second call is when you create an instance of a subclass, new subtype (), because the constructor of the child class is called again, and the instance property of the parent class is also included in the child class. Although properties in an instance are found to overwrite properties in the prototype when looking for properties, this is certainly a performance impact. So how do you avoid this problem?

Four, parasitic combined inheritance

We first need to know what the real purpose of these two calls to the constructor of the parent class is. For the first call, assigning an instance of the parent class to an instance of the subclass, we essentially need a pointer to the parent class prototype [[prototype]], which causes the parent class and subclass to connect through the prototype chain, and the parent class's instance properties we don't need, Its inheritance is implemented by invoking the second time in the constructor of the subclass. So, as long as we can think of a way to get a pointer to the parent prototype and add it to the prototype of the subclass, we can omit the first call.

Douglas Kest Rockford introduced a prototype inheritance method in 2006, in which a function was used:

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

In this function, a temporary empty constructor F is created first, then the parameter o is assigned to the prototype F, and finally an instance of F is returned. If we use this function in an inherited implementation, and pass the prototype object of the parent class as a parameter, it just satisfies our previous requirement that a copy of the parent prototype object is saved in the prototype F, and that f can be assigned to the prototype of the subclass, then the subclass can access all the prototype properties of the parent class. This process can be wrapped in the following function:

function Inheritprototype (subtype, supertype) {    var proto = object (supertype.prototype);    Proto.constructor = subtype;    Subtype.prototype = Proto;}

Inside the function, create a prototype copy of the parent class proto, then add the constructor property for it, and finally assign the copy to the child class. This makes it possible to establish a prototype chain without invoking the constructor of the parent class. Use this function instead of the statement that was assigned to the subclass prototype in the previous combination of inheritance.

function Supertype (name) {    this.name = name;    This.friends = ["Mike", "John"];} SuperType.prototype.sayName = function () {    alert (this.name);}; Function subtype (name,age) {    Supertype.call (this, name);         This.age = age;                 } Inheritprototype (subtype, supertype); SubType.prototype.sayAge = function () {    alert (this.age);};

This parasitic combined inheritance is the best way to inherit the current performance.

A detailed description of how JavaScript inherits

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.