当前位置:网站首页>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
边栏推荐
- c#使用oracle存储过程获取结果集实例
- JS get array subscript through array content
- LLVM之父Chris Lattner:为什么我们要重建AI基础设施软件
- OSPF multi zone configuration
- Swagger UI教程 API 文档神器
- ACdreamoj1110(多重背包)
- 3D face reconstruction: from basic knowledge to recognition / reconstruction methods!
- WEB功能测试说明
- FZU 1686 龙之谜 重复覆盖
- 966 minimum path sum
猜你喜欢

KDD 2022 | 通过知识增强的提示学习实现统一的对话式推荐

爱可可AI前沿推介(7.6)

HMS core machine learning service creates a new "sound" state of simultaneous interpreting translation, and AI makes international exchanges smoother
![[in depth learning] pytorch 1.12 was released, officially supporting Apple M1 chip GPU acceleration and repairing many bugs](/img/66/4d94ae24e99599891636013ed734c5.png)
[in depth learning] pytorch 1.12 was released, officially supporting Apple M1 chip GPU acceleration and repairing many bugs

防火墙基础之外网服务器区部署和双机热备

The biggest pain point of traffic management - the resource utilization rate cannot go up

Is this the feeling of being spoiled by bytes?

OneNote 深度评测:使用资源、插件、模版

The difference between break and continue in the for loop -- break completely end the loop & continue terminate this loop

Swagger UI教程 API 文档神器
随机推荐
Acdreamoj1110 (multiple backpacks)
OSPF多区域配置
El table table - sortable sorting & disordered sorting when decimal and% appear
Web开发小妙招:巧用ThreadLocal规避层层传值
互联网快讯:吉利正式收购魅族;胰岛素集采在31省全面落地
967- letter combination of telephone number
首批入选!腾讯安全天御风控获信通院业务安全能力认证
3D人脸重建:从基础知识到识别/重建方法!
Nodejs tutorial expressjs article quick start
技术分享 | 抓包分析 TCP 协议
【mysql】触发器
@PathVariable
Divide candy
Thinking about agile development
Pat 1078 hashing (25 points) ⼆ times ⽅ exploration method
Internet News: Geely officially acquired Meizu; Intensive insulin purchase was fully implemented in 31 provinces
缓存更新策略概览(Caching Strategies Overview)
el-table表格——sortable排序 & 出现小数、%时排序错乱
【力扣刷题】32. 最长有效括号
js 根据汉字首字母排序(省份排序) 或 根据英文首字母排序——za排序 & az排序