当前位置:网站首页>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
边栏推荐
- Torch learning notes (3) -- univariate linear regression model (self training)
- Zero length array
- Computer graduation design PHP campus address book telephone number inquiry system
- Win 11 major updates, new features love love.
- 平淡的生活里除了有扎破皮肤的刺,还有那些原本让你魂牵梦绕的诗与远方
- Computer graduation design PHP sports goods online sales system website
- [combinatorics] generating function (use generating function to solve the combination number of multiple sets R)
- 2022-2028 global lithium battery copper foil industry research and trend analysis report
- TypeScript 官网教程
- Day-27 database
猜你喜欢
SQL injection -day16
Have you learned the correct expression posture of programmers on Valentine's day?
2022-2028 global petroleum pipe joint industry research and trend analysis report
Xception for deeplab v3+ (including super detailed code comments and original drawing of the paper)
Gao Qing, Beijing University of Aeronautics and Astronautics: CIM is a natural quantum computing platform for graph data processing
Why can deeplab v3+ be a God? (the explanation of the paper includes super detailed notes + Chinese English comparison + pictures)
English grammar_ Noun classification
What kind of experience is it when the Institute earns 20000 yuan a month?
Administrative division code acquisition
SQL custom collation
随机推荐
Raft 日志复制
[combinatorics] generating function (positive integer splitting | unordered non repeated splitting example)
Pan for in-depth understanding of the attention mechanism in CV
SQL injection -day16
FBI warning: some people use AI to disguise themselves as others for remote interview
Implementation of cqrs architecture mode under Kratos microservice framework
[combinatorics] exponential generating function (properties of exponential generating function | exponential generating function solving multiple set arrangement)
Data analysis is popular on the Internet, and the full version of "Introduction to data science" is free to download
[combinatorics] generating function (use generating function to solve the number of solutions of indefinite equation)
Typescript configuration
Kratos微服务框架下实现CQRS架构模式
Bidding procurement scheme management of Oracle project management system
Common PostgreSQL commands
Enterprise custom form engine solution (12) -- form rule engine 2
Computer graduation design PHP sports goods online sales system website
22.2.14 -- station B login with code -for circular list form - 'no attribute' - 'needs to be in path selenium screenshot deviation -crop clipping error -bytesio(), etc
189. Rotation array
English grammar_ Noun classification
Computer graduation project PHP library book borrowing management system
Torch learning notes (6) -- logistic regression model (self training)