How to inherit in JavaScript _javascript skills

Source: Internet
Author: User
Tags pack

The concept of JS inheritance

JS commonly used in the following two kinds of inheritance methods:

Prototype chain inheritance (inheritance between objects)
Class inheritance (inheritance between constructors)
Since JS is not a real object-oriented language like Java, JS is object-based and does not have a class concept. Therefore, in order to achieve inheritance, you can use the prototype prototype mechanism JS or apply and call methods to achieve

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

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

JS can simulate the functionality of the implementation class by constructing functions and prototypes. In addition, the implementation of JS class-type inheritance relies on the prototype chain to realize.

Prototype inheritance and class inheritance

Class inheritance is a constructor that invokes a superclass within the subclass constructor.
Strict class inheritance is not very common, and is generally composed of:

Copy Code code as follows:

function Super () {
this.colors=["Red", "Blue"];
}

function Sub () {
Super.call (this);
}


Prototype inheritance is to create a new object with an existing object and to point the subclass's prototype to the parent class, which is equivalent to joining the prototype chain of the parent class.

Prototype chain inheritance

In order for subclasses to inherit the properties 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:

Copy Code code as follows:

<script>
function Parent () {
THIS.name = ' Mike ';
}

function Child () {
This.age = 12;
}
Child.prototype = new parent ();//child inherits the parent, through the archetype, forms the chain

var test = new Child ();
alert (test.age);
alert (test.name);//Get inherited property
Continue prototype chain inheritance
function Brother () {//brother construct
This.weight = 60;
}
Brother.prototype = new Child ()//Continue prototype chain inheritance
var brother = new brother ();
alert (brother.name);/inherits parent and child, pops up Mike
alert (brother.age);//Eject 12
</script>

The above prototype chain inheritance is missing One ring, that is object, all constructors inherit from object. And the Inheritance object is done automatically and does not need to be manually inherited by ourselves, so what are their dependencies?

Determining the relationship between a prototype and an instance

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

Copy Code code as follows:

Alert (brother instanceof Object)//true
Alert (test instanceof Brother);//false,test is a super class of Brother
Alert (brother instanceof Child);//true
Alert (brother instanceof Parent);//true

The isPrototypeOf () method returns true as long as the prototype in the prototype chain can be said to be the prototype of the instance derived from the prototype chain.

In JS, the inherited function is called a supertype (the parent class, the base class is also a row), and the inherited function is called the subtype (subclass, derived class). The use of prototype inheritance consists primarily of two questions:
First, the literal rewrite prototype breaks the relationship, uses the prototype of the reference type, and the subtype cannot pass parameters to the super type.

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

Borrowing constructors (class-style inheritance)

Copy Code code as follows:

<script>
function Parent (age) {
THIS.name = [' Mike ', ' Jack ', ' Smith '];
This.age = age;
}

function Child (age) {
Parent.call (This,age);
}
var test = new Child (21);
alert (test.age);//21
alert (test.name);//mike,jack,smith
Test.name.push (' Bill ');
alert (test.name);//mike,jack,smith,bill
</script>


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

Combined inheritance

Copy Code code as follows:

<script>
function Parent (age) {
THIS.name = [' Mike ', ' Jack ', ' Smith '];
This.age = age;
}
Parent.prototype.run = function () {
Return THIS.name + ' are both ' + this.age;
};
function Child (age) {
Parent.call (this,age);//object impersonate, pass to super type
}
Child.prototype = new Parent ();//prototype chain inheritance
var test = new Child (21);/write new Parent (21) also OK
Alert (Test.run ());//mike,jack,smith are both21
</script>

Combined inheritance is one of the most common methods of inheritance, and the idea behind it is to inherit the prototype property and method by using the prototype chain, and to inherit the instance property by borrowing the constructor. In this way, both functions are reused by defining methods on the prototype, and each instance has its own attribute.

Use of Call (): Invokes one method of an object, replacing the current object with another object.

Copy Code code as follows:

Call ([thisobj[,arg1[, arg2[, [,. argn]]]]

prototype Inheritance

This inheritance uses prototypes and creates new objects based on existing objects, without creating a custom type called a prototype inheritance

Copy Code code as follows:

<script>
function obj (o) {
function F () {}
F.prototype = O;
return new F ();
}
var box = {
Name: ' Trigkit4 ',
Arr: [' brother ', ' sister ', ' Baba ']
};
var B1 = obj (box);
alert (b1.name);//trigkit4

B1.name = ' Mike ';
alert (b1.name);//mike

alert (B1.arr);//brother,sister,baba
B1.arr.push (' parents ');
alert (B1.arr);//brother,sister,baba,parents

var b2 = obj (box);
alert (b2.name);//trigkit4
alert (B2.arr);//brother,sister,baba,parents
</script>

Prototype inheritance 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 way of inheriting is to combine the prototype + factory pattern to encapsulate the creation process.

Copy Code code as follows:

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

Small problem of modular inheritance

Modular inheritance is the most commonly used inheritance mode of JS, but the combination of inherited super types are called two times during use, once when the subtype is created, and the other is inside the child type constructor

Copy Code code as follows:

<script>
function Parent (name) {
THIS.name = name;
This.arr = [' elder brother ', ' sister ', ' parent '];
}

Parent.prototype.run = function () {
return this.name;
};

function Child (name,age) {
Parent.call (this,age);//Second Call
This.age = age;
}

Child.prototype = new Parent ();//First Call
</script>

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

Parasitic Modular Inheritance

Copy Code code as follows:

<script>
function obj (o) {
function F () {}
F.prototype = O;
return new F ();
}
function Create (parent,test) {
var f = obj (parent.prototype);//Create Object
F.constructor = test;//Enhanced Object
}

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)//through this implementation inheritance

var test = new Child (' TRIGKIT4 ', 21);
Test.arr.push (' nephew ');
alert (Test.arr);//
Alert (Test.run ());//Only Shared method

var test2 = new Child (' Jack ', 22);
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 a function, as follows:

Copy Code code as follows:

Define a global function
function foo () {
Console.log (This.fruit);
}

Define a global variable
var fruit = "Apple";
Customizing an Object
var pack = {
Fruit: "Orange"
};

Equivalent to Window.foo ();
foo.apply (window); "Apple", this is equal to window
The This = = Pack in foo
Foo.apply (Pack); "Orange"

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.