当前位置:网站首页>Six ways for JS to implement inheritance
Six ways for JS to implement inheritance
2022-07-24 17:29:00 【Drowned fish u】
JavaScript Want to achieve the purpose of inheritance : Reuse the properties and methods of another object .
1. Prototype chain inheritance
Let the prototype of a constructor be an instance of another type , So this constructor new The resulting instance has the attributes of the instance .
When trying to access the properties of an object , It doesn't just search for the object , It also searches for the prototype of the object , And the prototype of the object , Search up one by one , Until you find a property that matches a name or you reach the end of the prototype chain .
function Parent() {
this.isShow = true
this.info = {
name: "mjy",
age: 18,
};
}
Parent.prototype.getInfo = function() {
console.log(this.info);
console.log(this.isShow);
}
function Child() {};
Child.prototype = new Parent();
let Child1 = new Child();
Child1.info.gender = " male ";
Child1.getInfo(); // {name: 'mjy', age: 18, gender: ' male '} ture
let child2 = new Child();
child2.isShow = false
console.log(child2.info.gender) // male
child2.getInfo(); // {name: 'mjy', age: 18, gender: ' male '} false
advantage : The writing method is convenient and concise , Easy to understand .
shortcoming : Object instances share all inherited properties and methods . When teaching sub type instances , Can't pass parameters , Because this object is created at one time ( There's no way to customize ).
2. Inheritance by borrowing the constructor
function Parent(gender) {
this.info = {
name: "yhd",
age: 19,
gender: gender
}
}
function Child(gender) {
Parent.call(this, gender)
}
let child1 = new Child(' male ');
child1.info.nickname = 'xiaoma'
console.log(child1.info);
let child2 = new Child(' Woman ');
console.log(child2.info);
Call the parent type constructor inside the subtype constructor ; Use apply() or call() Method binds the constructor of the parent object to the child object .
advantage : It solves the problem that the prototype chain can't transfer parameters and the prototype sharing of the parent class .
shortcoming : The disadvantage of borrowing constructors is that methods are defined in constructors , Therefore, function reuse cannot be realized . Methods defined in the prototype of the parent type , Also invisible to subtypes , As a result, all types can only use constructor mode .
3. Combination inheritance ( Classic inheritance )
take Prototype chain and Borrow constructor Combine into one piece . Use prototype chain to implement inheritance of prototype properties and methods , The inheritance of instance property is realized by borrowing constructor . such , The function reuse is realized by defining the method on the prototype , It also ensures that each instance has its own properties
function Person(gender) {
console.log(' Number of executions ');
this.info = {
name: "mjy",
age: 19,
gender: gender
}
}
Person.prototype.getInfo = function () { // Use the prototype chain to inherit the properties and methods on the prototype
console.log(this.info.name, this.info.age)
}
function Child(gender) {
Person.call(this, gender) // Use constructor method to pass parameters
}
Child.prototype = new Person()
let child1 = new Child(' male ');
child1.info.nickname = 'xiaoma'
child1.getInfo()
console.log(child1.info);
let child2 = new Child(' Woman ');
console.log(child2.info);
The advantage is to solve the impact caused by prototype chain inheritance and borrowing constructor inheritance .
The disadvantage is that in any case , Both call the supertype constructor twice : One is when you create a subtype prototype , The other is inside the subtype constructor
4. Original pattern inheritance
Method 1 : Borrow constructor
In a function A Create a temporary constructor inside , The incoming object is then used as the prototype for the constructor , Finally returns a new instance of the temporary type . Essentially , function A Is a shallow copy of the incoming object .
function createObject(obj) {
function Fun() {}
Fun.prototype = obj
return new Fun()
}
let person = {
name: 'mjy',
age: 18,
hoby: [' sing ', ' jump '],
showName() {
console.log('my name is:', this.name)
}
}
let child1 = createObject(person)
child1.name = 'xxxy'
child1.hoby.push('rap')
let child2 = createObject(person)
console.log(child1)
console.log(child2)
console.log(person.hoby) // [' sing ', ' jump ', 'rap']
Method 2 :Object.create()
Object.create() Is to put the attributes of existing objects , Hang to the prototype of the new object , The new object is empty
ECMAScript 5 By increasing the Object.create() Method normalizes the concept of archetypal inheritance . This method takes two parameters : Objects as prototypes of new objects , And objects that define additional properties for new objects ( The second option ). When there is only one parameter ,Object.create() And the function here A The effect of the method is the same .
let person = {
name: 'mjy',
age: 19,
hoby: [' sing ', ' jump '],
showName() {
console.log('my name is: ', this.name)
}
}
let child1 = Object.create(person)
child1.name = 'xxt'
child1.hoby.push('rap')
let child2 = Object.create(person)
console.log(child1)
console.log(child2)
console.log(person.hoby) // [' sing ', ' jump ', 'rap']
Advantage is : You don't need to create constructors alone .
The disadvantage is that : The reference value contained in the property is always shared between related objects , A subclass instance cannot pass parameters to a parent class
\
5. Parasitic inheritance
The idea of parasitic inheritance and ( Parasitism ) ` Original pattern inheritance ` and ` Factory mode ` like , That is, create a function that encapsulates the inheritance process only , This function internally enhances the object in some way , Finally, return the object as if it did all the work .
function objectCopy(obj) {
function Fun() { };
Fun.prototype = obj;
return new Fun();
}
function createAnother(obj) {
let clone = objectCopy(obj);
clone.showName = function () {
console.log('my name is:', this.name);
};
return clone;
}
let person = {
name: "mjy",
age: 18,
hoby: [' sing ', ' jump ']
}
let child1 = createAnother(person);
child1.hoby.push("rap");
console.log(child1.hoby); // [' sing ', ' jump ', 'rap']
child1.showName(); // my name is: mjy
let child2 = createAnother(person);
console.log(child2.hoby); // [' sing ', ' jump ', 'rap']
advantage : Written in simple , You don't need to create constructors alone .
shortcoming : Adding functions to objects through parasitic inheritance can make functions difficult to reuse . Use parasitic inheritance to add functions to objects , It will reduce the efficiency due to the failure of function reuse ; This is similar to the constructor pattern .
6. Parasitic combinatorial inheritance
I talked about it before. , Composite inheritance is a commonly used classic inheritance pattern , however , The biggest problem with combinatorial inheritance is that in any case , Will call the parent constructor twice ; One is when you create a subtype , Once inside the constructor of a subtype . Parasitic composite inheritance is implemented to reduce the overhead of the parent constructor .
Inherit properties by borrowing constructors , Methods are inherited through a hybrid form of a prototype chain . Essentially , Is to use parasitic inheritance to inherit the prototype of supertype , Then assign the result to the prototype of the subtype .
function objectCopy(obj) {
function Fun() { };
Fun.prototype = obj;
return new Fun();
}
function inheritPrototype(child, parent) {
let prototype = objectCopy(parent.prototype);
prototype.constructor = child;
Child.prototype = prototype;
}
function Parent(name) {
this.name = name;
this.hoby = [' sing ', ' jump ']
}
Parent.prototype.showName = function () {
console.log('my name is:', this.name);
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
inheritPrototype(Child, Parent);
Child.prototype.showAge = function () {
console.log('my age is:', this.age);
}
let child1 = new Child("mjy", 18);
child1.showAge(); // 18
child1.showName(); // mjy
child1.hoby.push("rap");
console.log(child1.hoby); // [' sing ', ' jump ', 'rap']
let child2 = new Child("yl", 18);
child2.showAge(); // 18
child2.showName(); // yl
console.log(child2.hoby); // [' sing ', ' jump ']
Advantage is : High efficiency calls the parent constructor only once , And thus avoid unnecessary creation on sub prototypes , Redundant attribute . meanwhile , The prototype chain remains the same ; The disadvantage is that : Complex code
7.ES6、Class Implementation inheritance
principle ES5 Inheritance , The essence is to create the instance object of the subclass first this, Then add the method of the parent class to this above (Parent.apply(this)). ES6 The inheritance mechanism is quite different , The essence is to first instance the parent class object's properties and methods , Add to this above ( So you have to call it first super Method ), And then modify it with the constructor of the subclass this
advantage : The grammar is easy to understand , Easier to operate . shortcoming : Not all browsers support it class keyword lass Per
边栏推荐
- Atcoder beginer 202 e - count descendants (heuristic merge on heavy chain split tree for offline query)
- [GNN report] Tencent AI Lab Xu TingYang: graph generation model and its application in molecular generation
- Preliminary study of Oracle pl/sql
- Today, I met a 38K from Tencent, which let me see the ceiling of the foundation
- Heuristic merging (including examples of general formula and tree heuristic merging)
- UFW port forwarding
- Analog electricity - what is the resistance?
- Natbypass port forwarding
- Wrote a few small pieces of code, broke the system, and was blasted by the boss
- Code random notes_ Linked list_ 707 design linked list
猜你喜欢

2022 Asia International Internet of things exhibition

Getaverse,走向Web3的远方桥梁

Yolopose practice: one-stage human posture estimation with hands + code interpretation

A problem of MySQL database

二维卷积——torch.nn.conv2d的使用

Heuristic merging (including examples of general formula and tree heuristic merging)

Iftnews | Christie's launched its venture capital department, aiming at Web3 and metauniverse industries

Internet Download Manager Configuration

AutoCAD - join merge command

hcip第三天
随机推荐
JSP custom tag library --foreach
NC port forwarding
The most powerful programmer on the earth is equipped with a "three piece set". Do you know what it is?
Shardingsphere database read / write separation
微信朋友圈的高性能复杂度分析
Is computer monitoring true? Four experiments to find out
Fast power writing
NPM install reported -4058 error
2022 牛客暑期多校 K - Link with Bracket Sequence I(线性dp)
安全:如何为行人提供更多保护
Demonstration experiment of scrollbar for adjusting image brightness
Kyligence attended the Huawei global smart finance summit to accelerate the expansion of the global market
键盘输入操作
Why can't sizeof (ARR) / size (arr[0]) be used to calculate the array length inside the called function?
nc 端口转发
ROS主从机通信经验总结
Hcip fourth day notes
Portfwd port forwarding
Digital transformation must have digital thinking
Pat class A - check in and check out