当前位置:网站首页>JS learning notes OO create suspicious objects
JS learning notes OO create suspicious objects
2022-07-06 21:20:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm the king of the whole stack .
Asked 、 Factory introduction , Solve the problem of duplicate code
As mentioned earlier ,JS How to create objects in . It's not hard to find out , The main creation methods are , It's easy to create an object , If you create multiple similar objects, you will generate a lot of repetitive code .
solve : The factory model approach ( Add a method for creating objects , Pass in parameters to avoid repetition )
function createObject(name,age){
var obj =new Object(); // Create objects
obj.name = name;
obj.age = age;
obj.run = function(){
return this.name + this.age + ' In processing ...';
};
return obj; // Return object reference
};
Question two 、 Introduce constructors , Solve object recognition
Although the above method overcomes the problem of avoiding repeated code . But it also brings about the problem of not recognizing detailed objects , Method used internally new Object The way , Finally, return the object reference , All the objects created by calling this method return Object References to . Therefore use typeof or instanceof Operators cannot distinguish detailed objects .
solve : Constructors ( Improved factory method )
function Box(name,age){ // Create objects this.name = name; this.age = age; this.run = function(){ return this.name + this.age + ' In processing ...'; }; };
Compare : Careful children's shoes should be found , The difference between this method and the factory mode in question 1 is : omitted newObject() Clear text running process ; omitted return sentence , These are all run by the backstage itself .
The difference between constructors and ordinary functions lies in the way they are called , Must use new Operators or objects are called in a fake way .
Question three 、 introduce prototype Property object . Solve the sharing problem between objects
Every object will have a prototype, At the same time, it is also an object .
The purpose of use is to solve the sharing problem , The object created by calling the same constructor will share prototype Properties and methods in .
solve : Use prototype pattern to solve sharing
function Box() {} // Declare a constructor Box.prototype.name = 'Lee'; // Add attributes to the prototype Box.prototype.age = 100; Box.prototype.run = function () { // Add methods to the prototype return this.name + this.age + ' In processing ...'; };
Compare :
Constructor creation
Use prototypes to create
details : When calling properties or methods , Adopt the principle of proximity . First, check whether there is , If not, find the prototype . You can use isPrototypeOf(),hasOwnPrototy(),in Operators for related tests .
Question 4 、 Use combination , Solve the problem of sharing and transferring parameters
Prototype mode creation object omits the process of constructor parameter initialization , This is both its weakness and its strength , The disadvantage is that the object initialization value is the same , And suppose that the prototype attribute includes a reference type , Change an object . The corresponding properties of other objects will also be changed .
solve : Composite constructor + Archetypal model ( Solve the problem of sharing and transferring parameters )
function Box(name, age) { // Use constructors without sharing this.name = name; this.age = age; this. family = [' father ', ' mother ', ' Younger sister ']; }; Box.prototype = { // Shared use prototype pattern constructor : Box, run : function () { return this.name + this.age + this.family; } };
details : This way is actually to use constructors with prototypes . Analyze the object to be created , Put the content to be shared into the prototype , What you don't need is put in the constructor . This is the combination .
Optimize : Such a separate writing is inevitably a little strange . We combine these two parts
Dynamic prototype pattern ( Initialize the prototype when the shared method is called for the first time . It will not be initialized in the future )
function Box(name ,age) { // Encapsulate all information into the function body this.name = name; this.age = age; if (typeof this.run != 'function') {// Only in the initialization of the first call Box.prototype.run = function () { return this.name +this.age + ' In processing ...'; }; } }
Middle knot :
stay Study JS in , It is still very necessary to understand the orthodox object-oriented language , Here we learned to use constructors and prototypes to create objects , Understand the concept of both , For the back JS In depth study of object-oriented will be very helpful . Create different ways to solve problems in different situations , Understand these talents on demand .
Copyright notice : This article is the original article of the blogger , Blog , Do not reprint without permission .
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/117101.html Link to the original text :https://javaforall.cn
边栏推荐
- After working for 5 years, this experience is left when you reach P7. You have helped your friends get 10 offers
- 缓存更新策略概览(Caching Strategies Overview)
- Why do job hopping take more than promotion?
- Opencv learning example code 3.2.3 image binarization
- 966 minimum path sum
- KDD 2022 | 通过知识增强的提示学习实现统一的对话式推荐
- 爱可可AI前沿推介(7.6)
- 启动嵌入式间:资源有限的系统启动
- El table table - get the row and column you click & the sort of El table and sort change, El table column and sort method & clear sort clearsort
- First batch selected! Tencent security tianyufeng control has obtained the business security capability certification of the ICT Institute
猜你喜欢
2017 8th Blue Bridge Cup group a provincial tournament
【力扣刷题】32. 最长有效括号
Opencv learning example code 3.2.3 image binarization
【深度学习】PyTorch 1.12发布,正式支持苹果M1芯片GPU加速,修复众多Bug
【论文解读】用于白内障分级/分类的机器学习技术
[sliding window] group B of the 9th Landbridge cup provincial tournament: log statistics
OAI 5g nr+usrp b210 installation and construction
跨分片方案 总结
数据湖(八):Iceberg数据存储格式
20220211 failure - maximum amount of data supported by mongodb
随机推荐
The most comprehensive new database in the whole network, multidimensional table platform inventory note, flowus, airtable, seatable, Vig table Vika, flying Book Multidimensional table, heipayun, Zhix
document. Usage of write () - write text - modify style and position control
el-table表格——获取单击的是第几行和第几列 & 表格排序之el-table与sort-change、el-table-column与sort-method & 清除排序-clearSort
[sliding window] group B of the 9th Landbridge cup provincial tournament: log statistics
每个程序员必须掌握的常用英语词汇(建议收藏)
for循环中break与continue的区别——break-完全结束循环 & continue-终止本次循环
在最长的距离二叉树结点
SAP UI5 框架的 manifest.json
Data Lake (VIII): Iceberg data storage format
Reviewer dis's whole research direction is not just reviewing my manuscript. What should I do?
R language for text mining Part4 text classification
启动嵌入式间:资源有限的系统启动
Seven original sins of embedded development
字符串的使用方法之startwith()-以XX开头、endsWith()-以XX结尾、trim()-删除两端空格
快讯:飞书玩家大会线上举行;微信支付推出“教培服务工具箱”
【论文解读】用于白内障分级/分类的机器学习技术
document.write()的用法-写入文本——修改样式、位置控制
Study notes of grain Mall - phase I: Project Introduction
The biggest pain point of traffic management - the resource utilization rate cannot go up
ICML 2022 | Flowformer: 任务通用的线性复杂度Transformer