当前位置:网站首页>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
边栏推荐
- Briefly describe the quantitative analysis system of services
- Computer graduation project PHP library book borrowing management system
- Zero length array
- TypeScript 官网教程
- [combinatorics] generating function (positive integer splitting | repeated ordered splitting | non repeated ordered splitting | proof of the number of repeated ordered splitting schemes)
- An academic paper sharing and approval system based on PHP for computer graduation design
- 4. Load balancing and dynamic static separation
- [leetcode周赛]第300场——6110. 网格图中递增路径的数目-较难
- What is SQL get connection
- Data analysis is popular on the Internet, and the full version of "Introduction to data science" is free to download
猜你喜欢

leetcode:11. 盛最多水的容器【双指针 + 贪心 + 去除最短板】

Computer graduation design PHP sports goods online sales system website

Kratos微服务框架下实现CQRS架构模式

There are several levels of personal income tax

NFT新的契机,多媒体NFT聚合平台OKALEIDO即将上线

Su embedded training - Day10
![Golang string (string) and byte array ([]byte) are converted to each other](/img/41/20f445ef9de4adf2a2aa97828cb67f.jpg)
Golang string (string) and byte array ([]byte) are converted to each other

MySQL duplicate check

Recommend a simple browser tab

组策略中开机脚本与登录脚本所使用的用户身份
随机推荐
Setinterval CPU intensive- Is setInterval CPU intensive?
Prototype inheritance..
Change the single node of Postgres database into master-slave
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
2022-2028 global petroleum pipe joint industry research and trend analysis report
企业级自定义表单引擎解决方案(十二)--表单规则引擎2
How do microservices aggregate API documents? This wave of operation is too good
Administrative division code acquisition
Gao Qing, Beijing University of Aeronautics and Astronautics: CIM is a natural quantum computing platform for graph data processing
Recent learning experience
Real time split network (continuous update)
Usage of laravel conditional array in
What is SQL get connection
Have you learned the correct expression posture of programmers on Valentine's day?
编程中常见的 Foo 是什么意思?
[combinatorics] generating function (use generating function to solve the number of solutions of indefinite equation)
English语法_名词 - 分类
多媒体NFT聚合平台OKALEIDO即将上线,全新的NFT时代或将来临
How to read the source code [debug and observe the source code]
[combinatorics] generating function (positive integer splitting | basic model of positive integer splitting | disordered splitting with restrictions)