<! DOCTYPE html>
The concept of JS inheritancejs
The following two ways of inheriting are commonly used:
原型链继承(对象间的继承)类式继承(构造函数间的继承)
Because js
unlike the java
real object-oriented language, which is js
object-based, it does not have the concept of a class. Therefore, to achieve inheritance, you can use js
the prototype prototype mechanism or use apply
and call
methods to achieve
In object-oriented languages, we use it 类
to create a custom object. However js
, all things are objects, so what is the way to create a custom object? This is the prototype that needs to be used js
:
We can simply think of prototype
as a template, the newly created custom object is prototype
a copy of the template () (actually not a copy but a link, but the link is not visible, the newly instantiated object has an invisible __Proto__
pointer inside, pointing to the prototype object).
js
The functionality of the implementation class can be simulated by constructors and prototypes. In addition, the js
implementation of class-based inheritance is also based on the prototype chain.
Prototype inheritance and class-style 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);}
原型式继承
is to create a new object with an existing object, to point the prototype of the subclass to the parent class, which is equivalent to adding the parent class to the prototype chain
Prototype chain inheritanceIn 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> functionParent(){THIS.name =' Mike '; }functionChild(){This.age =12; } Child.prototype =New Parent (); //child inherits the parent, through the prototype, forms the chain var test = new Child (); alert (test.age); alert (test.name); //get inherited properties //continue prototype chain inheritance function brother () { //brother constructs this.weight = 60;} Brother.prototype = new Child (); Continue the prototype chain inheritance var brother = new brother (); alert (brother.name); Span class= "Hljs-comment" >//inherits the parent and child, pops up Mike Alert (Brother.age); //pop 12</SCRIPT>
The above prototype chain inheritance is also missing a link, that is Object
, all the constructors are inherited from Object
. and inheritance Object
is done automatically, and does not require our own manual inheritance, then what are their dependencies?
Determining the relationship between prototypes and instancesThere are two ways to determine the relationship between a prototype and an instance. Operators instanceof
and isPrototypeof()
methods:
instanceof Object)//truealert(test instanceof Brother);//false,test 是brother的超类alert(brother instanceof Child);//truealert(brother instanceof Parent);//true
As long as it is a prototype in the prototype chain, it can be said that the prototype chain-derived instances of the prototype, so the isPrototypeof()
method will also returntrue
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> functionparent (age) {this.name = [this.age = age; } function Childthis,age);} var test = new Child (21); alert ( Test.age); //21 alert (test.name); //mike,jack,smith Test.name.push (//mike,jack,smith,bill</script
Although the use of constructors solves just two problems, but there is no prototype, then reuse is impossible to talk about, so we need 原型链+借用构造函数
the pattern that this pattern is called combinatorial inheritance
Combining inheritance<Script> functionParent(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); new Parent (); var test = new Child (21); Span class= "Hljs-comment" >//write new Parent (21) also line alert (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.
call()
Usage: Invokes one method of an object, replacing the current object with another object.
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
Prototype inheritanceThis inheritance uses prototypes and creates new objects based on existing objects, without having to create custom types in a way called原型式继承
<Script> functionObj(o) {functionF() {} f.prototype = O;Returnnew F (); var box = {name: ' TRIGKIT4 ', arr: [ ' 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 first obj()
creates a temporary constructor inside the function, then takes the incoming object as a prototype of the constructor, and finally returns a new instance of the temporary type.
Parasitic inheritanceThis inheritance is done by combining the prototype + factory model to encapsulate the process of creation.
<script> function create(o){ var f= obj(o); f.run = function () { return this.arr;//同样,会共享引用 }; return f; }</script>
Small problems with combined inheritanceCombined inheritance is the js
most commonly used inheritance pattern, but the combination of inherited super types is called two times during use, when the subtype is created and the other is inside the subtype constructor
<Script> functionParentthis.name = name; this.arr = [ ' elder brother ', ' sister ', ' parents '; } Parent.prototype.run = function () {return this.name;}; function child this,age); this.age = Age;} Child.prototype = new Parent (); </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> functionObj(o) {functionF() {} f.prototype = O;ReturnNew F (); }functionCreate(parent,test) {var f = obj (Parent.prototype);Create object f.constructor = Test;Enhanced Object}functionParent(name) {THIS.name = name;This.arr = [' Brother ',' Sister ',' Parents ']; } Parent.prototype.run =function() {ReturnTHIS.name; };function Child this,name); this.age =age;} Inheritprototype (Parent,child); //through here to achieve inheritance var test = new Child ( Span class= "hljs-string" > ' TRIGKIT4 ', 21); Test.arr.push (//only shared methods var test2 = new Child ( Span class= "hljs-string" > ' Jack ', 22); alert (Test2.arr); //reference Problem resolution </SCRIPT>
Call and applyThe global function apply
and the call
pointer that can be used to change the function this
are as follows:
//define a global function function foo () { Console.log (this.fruit);} //defines a global variable var fruit = "Apple"; Span class= "hljs-comment" >//customizing an object var pack = {fruit: "Orange" }; //equivalent to Window.foo (); Foo.apply (window); //"Apple" at which time this equals window //the This = = = Pack foo.apply in Foo at this time ( Pack); //"Orange"
Bo master recently poor eat soil, if after reading the contents of this article feel that you have some help, think Bo Master Update of the diligent point, you do not sweep it (message you want to learn the front-end technology, Bo Master is free to update yo)
The cliché of the 5 inheritance of JavaScript