当前位置:网站首页>Know what it is, and know why, JS object creation and inheritance [summary and sorting]
Know what it is, and know why, JS object creation and inheritance [summary and sorting]
2022-07-03 18:41:00 【51CTO】
Preface
stay 6 In yuegeng's article, it is said in scattered words JS Object creation and object inheritance for , Some workers expressed doubts about this , it is to be noted that : These are two different but related things , Don't confuse !
These articles are :
- Suddenly look back ,“ factory 、 structure 、 Prototype ” Design patterns , In the dim light
- JS Essence , Prototype chain inheritance and constructor inheritance “ Trouble ”
- “ factory 、 structure 、 Prototype ” Design pattern and JS Inherit
- JS Advanced programming 4:class The point of inheritance
- JS class It's not just a simple grammar sugar !
This is a summary , Let's explore !! To rush
objects creating
It's not hard to find out , Every article is inseparable from the factory 、 structure 、 Prototype this 3 At least one of the design patterns !
I can't help asking :JS Why do we have to use this 3 A design pattern ??
Trace the origin of the original , Let's start with object creation :
We are used to declaring objects like this ( No design patterns )
When there are two or more such objects to declare , It is impossible to copy and write all the time :
Write it like this :
- It's hard to write , There's a lot of repetitive code ;
- Not conducive to revision , For example, when car Object needs to add, delete or change a property , It needs to be added, deleted and modified in several places ;
Factory function
It must be encapsulated , The first reaction , Sure With the help of a function To help us create objects in batch ~
So :
function makeCar(price,color,performance){
let obj = {}
obj.price = price
obj.color= color
obj.run = ()=>{console.log(performance)}
return obj
}
let car1= makeCar("100","white","run fast")
let car2= makeCar("200","black","run slow")
let car3= makeCar("300","red","broken")
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
This is the factory design pattern in JS The origin of the application when creating objects ~
Come here , about 【 objects creating 】 Come on , It should be enough ? yes , Without considering expansion , It's almost enough .
But there is a new demand at this time , Need to create car4、car5、car6 object , They need to add a new one to the original one brand attribute , Will be how to write ?
First reaction , Directly modifying makeCar
function makeCar(price,color,performance,brand){
let obj = {}
obj.price = price
obj.color= color
obj.run = ()=>{console.log(performance)}
obj.brand = brand
return obj
}
let car4= makeCar("400","white","run fast","benz")
let car5= makeCar("500","black","run slow","audi")
let car6= makeCar("600","red","broken","tsl")
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
Write it like this , no way , Will affect the original car1、car2、car3 object ;
Then write another one makeCarChild Is the factory function OK ?
function makeCarChild (price,color,performance,brand){
let obj = {}
obj.price = price
obj.color= color
obj.run = ()=>{console.log(performance)}
obj.brand = brand
return obj
}
let car4= makeCarChild("400","white","run fast","benz")
let car5= makeCarChild("500","black","run slow","audi")
let car6= makeCarChild("600","red","broken","tsl")
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
Yes, yes , It's just too much trouble , Properties before full copy , establish N A similar factory , It seems so stupid ...
Constructors
So , In the factory design pattern , Developed : Constructor design pattern , To solve the above reuse ( That is inheritance ) The problem of .
function MakeCar(price,color,performance){
this.price = price
this.color= color
this.run = ()=>{console.log(performance)}
}
function MakeCarChild(brand,...args){
MakeCar.call(this,...args)
this.brand = brand
}
let car4= new MakeCarChild("benz","400","white","run fast")
let car5= new MakeCarChild("audi","500","black","run slow")
let car6= new MakeCarChild("tsl","600","red","broken")
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
Constructors are different from factory functions :
- Function names are usually capitalized ;
- When creating objects, you need new keyword (new I will not repeat the process here , Previous articles have );
- Function does not return, But through this Binding to implement the ;
Only this and nothing more , The reuse of factory functions also solves .
structure + Prototype
The new problem is , We can't find the prototype chain from MakeCarChild find MakeCar
No matter how you find it on the prototype chain , I can't get it from MakeCarChild find MakeCar
That means : A subclass cannot inherit properties on a parent class prototype
Here is a question to consider : Why? “ To find out from the prototype chain ” Very important ? Why? “ The subclass should inherit the attributes on the parent class prototype ”? It depends this Can't you find it by binding ?
So , Constructor design pattern + Prototype design patterns Of 【 Combination inheritance 】 emerge as the times require
function MakeCar(price,color,performance){
this.price = price
this.color= color
this.run = ()=>{console.log(performance)}
}
function MakeCarChild(brand,...args){
MakeCar.call(this,...args)
this.brand = brand
}
MakeCarChild.prototype = new MakeCar() // The prototype inherits the constructor of the parent class
MakeCarChild.prototype.constructor = MakeCarChild // Reset constructor
let car4= new MakeCarChild("benz","400","white","run fast")
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
Now find the prototype , I can find it :
Actually , Can get here , It's already very good , There should be , The writing is not very complicated .
factory + structure + Prototype
but , There are always people who are pursuing the ultimate .
The above composite inheritance , Parent constructor called twice , Once it was call The process of , One is prototype inheritance new The process of , If every instantiation , Are called repeatedly , It must not be desirable , How to avoid ?
factory + structure + Prototype = Parasitic combination inheritance emerge as the times require
The core is , Create a new broker through the factory function F( ), Copy a prototype object of the parent class , And then assign it to the prototype of the subclass ;
function object(o) { // Factory function
function F() {}
F.prototype = o;
return new F(); // new An empty function , The memory occupied is very small
}
function inherit(child, parent) { // Prototype inheritance
var prototype = object(parent.prototype)
prototype.constructor = child
child.prototype = prototype
}
function MakeCar(price,color,performance){
this.price = price
this.color= color
this.run = ()=>{console.log(performance)}
}
function MakeCarChild(brand,...args){ // Constructors
MakeCar.call(this,...args)
this.brand = brand
}
inherit(MakeCarChild,MakeCar)
let car4= new MakeCarChild("benz","400","white","run fast")
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
ES6 class
To the later ,ES6 Of class A grammatical sugar inherited as a parasitic combination :
class MakeCar {
constructor(price,color,performance){
this.price = price
this.color= color
this.performance=performance
}
run(){
console.log(console.log(this.performance))
}
}
class MakeCarChild extends MakeCar{
constructor(brand,...args){
super(brand,...args);
this.brand= brand;
}
}
let car4= new MakeCarChild("benz","400","white","run fast")
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
Interested workers , May have a look ES6 It can be interpreted as ES5 Code for : Prototype and prototype chain - ES6 Class The underlying implementation principle of #22
Objects and functions
Finally, Ben Gua wants to talk about JS The relationship between objects and functions :
Even if you declare an object like this ,let obj = {} , It is also constructed by the constructor Object Constructed from :
stay JS in , Everything is object , Objects are constructed from functions , Functions are also objects .
Corresponding to the meaning in the code :
- All implicit prototypes of constructors are equal to Function The display prototype of , Functions are all created by Function Constructed ,Object Constructors are no exception ;
- The implicit prototype of the display prototype of all constructors , All equal to Object The display prototype of ,Function No exception ;
This design is really a big speechless , Big tangle , Big trouble ...
You can only remember first according to the wrong explanation mentioned before :Function It's God , God created everything ;Object Is everything . All things are created by God ( Objects are constructed from functions ), God himself belongs to a substance ( Functions themselves are objects );
For this article , Inherit , In fact, the parent-child constructor inherits , Then the constructor instantiates the object , So as to realize the inheritance of objects .
Who is inheriting ? function ? object ? All right ~~
Summary
This chapter starts with creating objects , The factory function , It can be a basic layer of packaging ;
Until then , Expansion of the factory , Evolve to constructor ;
Then based on the characteristics of the prototype , structure + Prototype , Get composite inheritance ;
And pursue the ultimate , Speaking of parasitic assemblages ;
Let's talk about simplified writing Es6 class ;
And finally, the thinking of objects and functions .
Come here first ~~
OK, The above is the sharing of this article . Like, follow the comments , Help good writing
I'm Anthony nuggets 100 Ten thousand popular front-end technology bloggers INFP Writing personality persistence 1000 Japanese Geng Wen Pay attention to me , Anthony spent the long programming years with you
边栏推荐
- Getting started with JDBC
- Reading a line from ifstream into a string variable
- Pan for in-depth understanding of the attention mechanism in CV
- Zero length array
- After the festival, a large number of people change careers. Is it still time to be 30? Listen to the experience of the past people
- English grammar_ Adjective / adverb Level 3 - multiple expression
- Raft log replication
- 2022-2028 global solid phase extraction column industry research and trend analysis report
- Install apache+php+mysql+phpmyadmin xampp and its error resolution
- Computer graduation design PHP sports goods online sales system website
猜你喜欢

Administrative division code acquisition

Mature port AI ceaspectus leads the world in the application of AI in terminals, CIMC Feitong advanced products go global, smart terminals, intelligent ports, intelligent terminals

2022-2028 global physiotherapy clinic industry research and trend analysis report
知其然,而知其所以然,JS 对象创建与继承【汇总梳理】

Prototype inheritance..
![[combinatorics] generating function (generating function application scenario | using generating function to solve recursive equation)](/img/e6/9880e708aed42dc82c94aea002020c.jpg)
[combinatorics] generating function (generating function application scenario | using generating function to solve recursive equation)
![How to read the source code [debug and observe the source code]](/img/87/3cb25eb0301dc8046e39b997411e59.jpg)
How to read the source code [debug and observe the source code]

Nodejs (01) - introductory tutorial

2022.02.11

CTO and programmer were both sentenced for losing control of the crawler
随机推荐
How to expand the capacity of golang slice slice
199. Right view of binary tree - breadth search
Prototype inheritance..
2022-2028 global physiotherapy clinic industry research and trend analysis report
[combinatorics] generating function (positive integer splitting | basic model of positive integer splitting | disordered splitting with restrictions)
[combinatorics] generating function (use generating function to solve the combination number of multiple sets R)
[Yu Yue education] world reference materials of Microbiology in Shanghai Jiaotong University
Sepconv (separable revolution) code recurrence
Golang string (string) and byte array ([]byte) are converted to each other
SQL injection -day16
虚拟机和开发板互Ping问题
Implementation of cqrs architecture mode under Kratos microservice framework
Torch learning notes (5) -- autograd
Suffix derivation based on query object fields
English語法_名詞 - 分類
多媒体NFT聚合平台OKALEIDO即将上线,全新的NFT时代或将来临
Sensor 调试流程
2022-2028 global sepsis treatment drug industry research and trend analysis report
Closure and closure function
How to track the real-time trend of Bank of London