当前位置:网站首页>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
边栏推荐
- NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon
- 论文阅读 GloDyNE Global Topology Preserving Dynamic Network Embedding
- What is the function of registering DLLs- What does registering a DLL do?
- shell 脚本中关于用户输入参数的处理
- NFT新的契机,多媒体NFT聚合平台OKALEIDO即将上线
- Have you learned the correct expression posture of programmers on Valentine's day?
- Torch learning notes (7) -- take lenet as an example for dataload operation (detailed explanation + reserve knowledge supplement)
- 平淡的生活里除了有扎破皮肤的刺,还有那些原本让你魂牵梦绕的诗与远方
- Torch learning notes (1) -- 19 common ways to create tensor
- [combinatorics] generating function (example of using generating function to solve the number of solutions of indefinite equation)
猜你喜欢
SQL injection -day16
NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon
Data analysis is popular on the Internet, and the full version of "Introduction to data science" is free to download
Computer graduation design PHP campus address book telephone number inquiry system
2022-2028 global physiotherapy clinic industry research and trend analysis report
Torch learning notes (3) -- univariate linear regression model (self training)
平淡的生活里除了有扎破皮肤的刺,还有那些原本让你魂牵梦绕的诗与远方
SQL custom collation
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
English语法_名词 - 分类
随机推荐
Golang string (string) and byte array ([]byte) are converted to each other
Redis cache avalanche, penetration, breakdown
12、 Service management
[combinatorics] exponential generating function (example of exponential generating function solving multiple set arrangement)
What is the function of registering DLLs- What does registering a DLL do?
平淡的生活里除了有扎破皮肤的刺,还有那些原本让你魂牵梦绕的诗与远方
199. Right view of binary tree - breadth search
2022-2028 global plasmid DNA cdmo industry research and trend analysis report
Multifunctional web file manager filestash
Computer graduation design PHP campus address book telephone number inquiry system
2022-2028 global scar care product industry research and trend analysis report
Su embedded training - Day10
Real time split network (continuous update)
Sensor debugging process
What is SQL get connection
2022-2028 global physiotherapy clinic industry research and trend analysis report
Sepconv (separable revolution) code recurrence
How does GCN use large convolution instead of small convolution? (the explanation of the paper includes super detailed notes + Chinese English comparison + pictures)
2022.02.11
Theoretical description of linear equations and summary of methods for solving linear equations by eigen