A detailed description of how JavaScript inherits

Source: Internet
Author: User

The concept of JS inheritance

JS commonly used in the following two ways to inherit:

Prototype chain inheritance (inheritance between objects) class inheritance (inheritance between constructors)

Since JS is not really an object-oriented language like Java, JS is Object-based and has no concept of class. Therefore, in order to achieve inheritance, you can use the JS prototype prototype mechanism or use the Apply and call method to achieve

In object-oriented languages, we use classes to create a custom object. However, all things in JS are objects, so what is the way to create a custom object? This will require the use of JS prototype:

We can simply think of prototype as a template, the newly created custom object is a copy of the template (prototype) (actually not a copy but a link, but this link is not visible, the newly instantiated object inside there is an invisible __proto__ pointer, Point to the prototype object).

JS can simulate the implementation of the function of the class by means of constructors and prototypes. In addition, the implementation of JS-class inheritance is also based on the prototype chain.

Prototype inheritance and class-style inheritance

A class-type inheritance is a constructor that calls a super-type inside a subtype constructor.

Strict class-type inheritance is not very common, and is generally combined with:

function Super () {  this. colors=["red","blue" ];} function Sub () {super.call (this);}

Prototype inheritance is the creation of new objects with existing objects, and the prototype of the subclass to the parent class, which is equivalent to joining the parent class as the prototype chain

Prototype chain inheritance

In order for subclasses to inherit the attributes of the parent class (also including methods), you first need to define a constructor. The new instance of the parent class is then assigned to the constructor's prototype. The code is as follows:

<script>function Parent () { This. Name ='Mike';} function Child () { This. Age = A;} Child.prototype=NewParent ();//Child inherits the parent, through the prototype, forms the chain varTest =NewChild (); alert (test.age); alert (test.name) ;//Get the inherited property//continuation of the prototype chain inheritancefunction Brother () {//Brother Construction     This. Weight = -;} Brother.prototype=NewChild ();//continuation of the prototype chain inheritancevarBrother =NewBrother (); alert (brother.name);//inherits the parent and child, pops up Mikealert (brother.age);//pop Up</script>

The above prototype chain inheritance is also missing a link, that is, object, all constructors are inherited from object. And inheriting object is automatic, do not need our own manual inheritance, then what is their affiliation?

Determining the relationship between prototypes and instances

There are two ways to determine the relationship between a prototype and an instance. operator instanceof and isPrototypeOf () methods:

Alert (brother instanceof Object)//truealert (test instanceof brother); // False,test is Brother's Super class Alert (brother instanceof Child); // true Alert (brother instanceof Parent); // true

The isPrototypeOf () method also returns true as long as the prototype in the prototype chain is a prototype of an instance derived from the prototype chain.

In JS, the inherited function is called the supertype (the parent class, the base class also rows), and the inherited function is called the subtype (subclass, derived class). The use of prototype inheritance is primarily composed of two questions:

The first is that the literal rewrite prototype breaks the relationship, uses the prototype of the reference type, and the subtype cannot pass the parameter to the super type.

Pseudo-class solves the problem that reference sharing and super type cannot be referenced, we can use "borrow constructor" technique

Borrowing constructors (class-type Inheritance)

<script>function Parent (age) { This. name = ['Mike','Jack','Smith'];  This. Age =Age ;} function Child (age) {Parent.call ( This, age);}varTest =NewChild ( +); alert (test.age);// +alert (test.name);//Mike,jack,smithTest.name.push ('Bill'); alert (test.name);//Mike,jack,smith,bill</script>

Although the use of constructors solves just two kinds of problems, but there is no prototype, then reuse is impossible to talk about, so we need the prototype chain + borrowing constructor mode, this pattern is called combinatorial inheritance

Combining inheritance

<script>function Parent (age) { This. name = ['Mike','Jack','Smith'];  This. Age =Age ;} Parent.prototype.run=function () {return  This. Name +'is both'+ This. Age;}; function Child (age) {Parent.call ( This, age);} Child.prototype=NewParent ();varTest =NewParent ( +);//Write new Child (21) also OKalert (Test.run ());//Mike,jack,smith is both21</script>

Combined inheritance is a common method of inheritance, and the idea behind it is to use the prototype chain to inherit the prototype properties and methods, and to implement the inheritance of the instance attributes by borrowing the constructor function. This enables the reuse of functions both by defining methods on the prototype and ensuring that each instance has its own properties

Prototype inheritance

This inheritance is called prototype inheritance by prototyping and creating new objects based on existing objects without having to create custom types.

<script>function obj (o) {function F () {} F.prototype=o; return NewF ();}varbox ={name:'TRIGKIT4', arr: ['Brother','Sister','Baba']};varB1 =obj (box); alert (b1.name);//TRIGKIT4B1.name='Mike'; alert (b1.name);//Mikealert (B1.arr);//Brother,sister,babaB1.arr.push ('Parents'); alert (B1.arr);//brother,sister,baba,parents varB2 =obj (box); alert (b2.name);//TRIGKIT4alert (B2.arr);//brother,sister,baba,parents</script>

Prototype inheritance first creates a temporary constructor inside the obj () function, then takes the incoming object as a prototype of the constructor, and finally returns a new instance of the temporary type.

Parasitic inheritance

This inheritance is done by combining the prototype + factory model to encapsulate the process of creation.

<script>function Create (o) {  var f== function () {  returnthis
    .arr; // Similarly, references are shared  };  return  F;} </script>

Small problems with combined inheritance

Combined inheritance is the most commonly used inheritance mode for JS, but the combination of inherited super types is called two times during the use process, once the subtype is created, and the other is inside the subtype constructor.

<script>function Parent (name) { This. Name =name;  This. arr = ['Brother','Sister','Parents'];} Parent.prototype.run=function () {return  This. Name;}; function Child (name,age) {Parent.call ( This, age);//Second Call     This. Age =Age ;} Child.prototype=NewParent ();//First time Call</script>

The above code is the previous combination of inheritance, then the parasitic combination inheritance, resolved the problem of two calls.

Parasitic combined inheritance

<script>function obj (o) {function F () {} F.prototype=o; return NewF ();} function Create (parent,test) {varf = obj (Parent.prototype);//Creating ObjectsF.constructor = test;//Enhanced Objects}function Parent (name) { This. Name =name;  This. arr = ['Brother','Sister','Parents'];} Parent.prototype.run=function () {return  This. Name;}; function Child (name,age) {Parent.call ( This, name);  This. Age =Age ;} Inheritprototype (parent,child);//inheritance is achieved through thisvarTest =NewChild ('TRIGKIT4', +); Test.arr.push ('nephew'); alert (Test.arr);//Alert (Test.run ());//only methods are sharedvarTest2 =NewChild ('Jack', A); alert (Test2.arr);//Reference Problem Resolution</script>

Call and apply

Global functions apply and call can be used to change the direction of this in the function as follows:

//define a global functionfunction foo () {Console.log ( This. fruit);} //define a global variablevarFruit ="Apple";//customizing an ObjectvarPack ={fruit:"Orange"}; //equivalent to Window.foo ();foo.apply (window);//"Apple", at which point this is equal to window//the This = = = Pack in foofoo.apply (pack);//"Orange"

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.