Home > Article > Web Front-end > Detailed explanation of inheritance methods in JS
This article mainly introduces the detailed explanation of inheritance methods in JavaScript. This article explains the concept of js inheritance, prototypal inheritance and class inheritance, prototype chain inheritance, class inheritance, combination inheritance, prototypal inheritance, etc., which requires Friends can refer to
The concept of js inheritance
The following two inheritance methods are commonly used in js:
Prototype chain inheritance (between objects Inheritance)
Class inheritance (Inheritance between constructors)
Since js is not a truly object-oriented language like java, js is based on objects, it There is no concept of classes. Therefore, if you want to implement inheritance, you can use the prototype mechanism of js or the apply and call methods to achieve
In object-oriented languages, we use classes to create a custom object. However, everything in js is an object, so how to create a custom object? This requires the use of js prototype:
We can simply regard prototype as a template. The newly created custom objects are all copies of this template (prototype) (actually not a copy but a copy) Link, but this link is invisible. There is an invisible Proto pointer inside the newly instantiated object, pointing to the prototype object).
js can simulate the functions of the class through constructors and prototypes. In addition, the implementation of js class inheritance also relies on the prototype chain.
Prototypal inheritance and class inheritance
Class inheritance is to call the supertype constructor inside the subtype constructor.
Strict class inheritance is not very common, and is usually used in combination:
The code is as follows:
function Super(){ this.colors=["red","blue"]; } function Sub(){ Super.call(this); }
Prototypal inheritance uses existing objects Creating a new object and pointing the prototype of the subclass to the parent class is equivalent to joining the prototype chain of the parent class
Prototype chain inheritance
In order to let the subclass To inherit the attributes (including methods) of the parent class, you first need to define a constructor. Then, assign the new instance of the parent class to the constructor's prototype. The code is as follows:
The code is as follows:
<script> function Parent(){ this.name = 'mike'; } function Child(){ this.age = 12; } Child.prototype = new Parent();//Child继承Parent,通过原型,形成链条 var test = new Child(); alert(test.age); alert(test.name);//得到被继承的属性 //继续原型链继承 function Brother(){ //brother构造 this.weight = 60; } Brother.prototype = new Child();//继续原型链继承 var brother = new Brother(); alert(brother.name);//继承了Parent和Child,弹出mike alert(brother.age);//弹出12 </script>
There is still one missing link in the above prototype chain inheritance, which is Object. All constructors inherit from Object. Inheriting Object is completed automatically and does not require us to inherit manually. So what is their affiliation?
Determine the relationship between prototypes and instances
The relationship between prototypes and instances can be determined in two ways. Operator instanceof and isPrototypeof() methods:
The code is as follows:
alert(brother instanceof Object)//true alert(test instanceof Brother);//false,test 是brother的超类 alert(brother instanceof Child);//true alert(brother instanceof Parent);//true
As long as it is a prototype that appears in the prototype chain, it can be said to be the prototype of the instance derived from the prototype chain , therefore, the isPrototypeof() method will also return true
In js, the inherited function is called the supertype (parent class, base class is also acceptable), and the inherited function is called the subtype (subclass, Derived class). There are two main problems with using prototypal inheritance:
First, overriding the prototype with literals will break the relationship, using the prototype of the reference type, and the subtype cannot pass parameters to the supertype.
Pseudo classes solve the problem of reference sharing and the inability to pass parameters of super types. We can use the "borrowed constructor" technology
Borrowed constructor (class inheritance)
The code is 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 borrowing the constructor solves the two problems just now, without a prototype, reuse is impossible, so we need a prototype chain + a borrowed constructor mode, this mode is called combined inheritance
Combined inheritance
The code is 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);//对象冒充,给超类型传参 } Child.prototype = new Parent();//原型链继承 var test = new Child(21);//写new Parent(21)也行 alert(test.run());//mike,jack,smith are both21 </script>
Combined inheritance is a commonly used one An inheritance method, the idea behind it is to use the prototype chain to realize the inheritance of prototype properties and methods , and to realize the inheritance of instance properties by borrowing the constructor. In this way, function reuse is achieved by defining methods on the prototype, and each instance is guaranteed to have its own attributes.
Usage of call(): Call a method of an object and replace the current object with another object.
The code is as follows:
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
Prototypal inheritance
<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>Prototypal inheritance first creates a temporary constructor inside the obj() function, Then the passed in object is used as the prototype of this constructor, and finally a new instance of this temporary type is returned.
Parasitic inheritance
This inheritance method combines the prototype +factory pattern in order to encapsulate the creation process.
<script> function create(o){ var f= obj(o); f.run = function () { return this.arr;//同样,会共享引用 }; return f; } </script>
Small problems with combined inheritance
组合式继承是js最常用的继承模式,但组合继承的超类型在使用过程中会被调用两次;一次是创建子类型的时候,另一次是在子类型构造函数的内部
代码如下:
<script> function Parent(name){ this.name = name; this.arr = ['哥哥','妹妹','父母']; } Parent.prototype.run = function () { return this.name; }; function Child(name,age){ Parent.call(this,age);//第二次调用 this.age = age; } Child.prototype = new Parent();//第一次调用 </script>
以上代码是之前的组合继承,那么寄生组合继承,解决了两次调用的问题。
寄生组合式继承
代码如下:
<script> function obj(o){ function F(){} F.prototype = o; return new F(); } function create(parent,test){ var f = obj(parent.prototype);//创建对象 f.constructor = test;//增强对象 } 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);//通过这里实现继承 var test = new Child('trigkit4',21); test.arr.push('nephew'); alert(test.arr);// alert(test.run());//只共享了方法 var test2 = new Child('jack',22); alert(test2.arr);//引用问题解决 </script>
call和apply
全局函数apply和call可以用来改变函数中this的指向,如下:
代码如下:
// 定义一个全局函数 function foo() { console.log(this.fruit); } // 定义一个全局变量 var fruit = "apple"; // 自定义一个对象 var pack = { fruit: "orange" }; // 等价于window.foo(); foo.apply(window); // "apple",此时this等于window // 此时foo中的this === pack foo.apply(pack); // "orange"
The above is the detailed content of Detailed explanation of inheritance methods in JS. For more information, please follow other related articles on the PHP Chinese website!