当前位置:网站首页>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
边栏推荐
- 跨分片方案 总结
- Data Lake (VIII): Iceberg data storage format
- WEB功能测试说明
- ICML 2022 | flowformer: task generic linear complexity transformer
- JS traversal array and string
- Set up a time server
- 防火墙基础之外网服务器区部署和双机热备
- Opencv learning example code 3.2.3 image binarization
- [sliding window] group B of the 9th Landbridge cup provincial tournament: log statistics
- Reviewer dis's whole research direction is not just reviewing my manuscript. What should I do?
猜你喜欢
Why do job hopping take more than promotion?
039. (2.8) thoughts in the ward
KDD 2022 | 通过知识增强的提示学习实现统一的对话式推荐
Study notes of grain Mall - phase I: Project Introduction
Manifest of SAP ui5 framework json
Performance test process and plan
跨分片方案 总结
互联网快讯:吉利正式收购魅族;胰岛素集采在31省全面落地
After working for 5 years, this experience is left when you reach P7. You have helped your friends get 10 offers
This year, Jianzhi Tencent
随机推荐
Web开发小妙招:巧用ThreadLocal规避层层传值
VIM basic configuration and frequently used commands
OneNote 深度评测:使用资源、插件、模版
启动嵌入式间:资源有限的系统启动
Why do job hopping take more than promotion?
MLP (multilayer perceptron neural network) is a multilayer fully connected neural network model.
数据湖(八):Iceberg数据存储格式
Regular expression collection
Aike AI frontier promotion (7.6)
Vim 基本配置和经常使用的命令
Study notes of grain Mall - phase I: Project Introduction
Pat 1085 perfect sequence (25 points) perfect sequence
Is this the feeling of being spoiled by bytes?
Deployment of external server area and dual machine hot standby of firewall Foundation
Fastjson parses JSON strings (deserialized to list, map)
Forward maximum matching method
分糖果
【Redis设计与实现】第一部分 :Redis数据结构和对象 总结
JS get array subscript through array content
document.write()的用法-写入文本——修改样式、位置控制