


Understand JavaScript object creation and object creation through prototypes
1. Several ways to create objects
1. Independent declaration mode
var box1 = new Object(); //声明第一个对象并给各属性赋值 box1.name = 'Lee'; box1.age = 100; box1.run = function () { return this.name + this.age + '运行中...'; }; alert(box.run()); var box2 = new Object(); //声明第二个对象并给属性赋值 box2.name = 'Jack'; box2.age = 200; box2.run = function () { return this.name + this.age + '运行中...'; }; alert(box2.run());
At this time, box2 and box1 are independent of each other. will be confused.
But in this way, every time you declare an object with the same structure, you have to add a piece of code, which is particularly inconvenient, so we have the following factory pattern.
2. Factory mode
function createObject(name, age) { //集中实例化的函数 var obj = new Object(); obj.name = name; obj.age = age; obj.run = function () { return this.name + this.age + '运行中...'; }; return obj; }
In this way, you only need to call the createObject() method every time you create a new object. At the same time, you can also pass parameters to initialize the object.
But since the objects produced by new are all subordinate to Object, when I want to make some distinctions in the nature of the objects produced by new, it will not work. At this time, there is a simpler constructor mode.
3. Constructor pattern
function Box(name, age) { this.name = name; this.age = age; this.run = function () { return this.name + this.age + '运行中...'; }; } var box1 = new Box('Lee', 100); var box2 = new Box('Jack', 200); alert(box1.run()); alert(box1 instanceof Box); //很清晰的识别他从属于Box
The constructor pattern largely solves the problem of object reuse and parameter initialization, and is the most commonly used new object pattern.
Note:
Herebox1.run != box2.run, because they determine the reference address, so It can be seen that the methods of the two objects are stored in different places and are two different methods.
But box1.run() == box2.run(), because they return the same value.
When you have an object, it will naturally involve the sharing of object attributes and methods (for example, in Java, subclasses share member variables and methods of the parent class).
To put it bluntly, the objects created by the constructor pattern are independent of each other (such as box1.run != box2.run above). If I want to share certain attributes between two objects, I must use a prototype. prototype.
2. Create objects through prototypes
1. Prototype mode
function Box() {} //声明一个构造函数 Box.prototype.name = 'Lee'; //在原型里添加属性 Box.prototype.age = 100; Box.prototype.arr = ['aaa','bbb']; Box.prototype.run = function () { //在原型里添加方法 return this.name + this.age + '运行中...'; }; var box1 = new Box(); var box2 = new Box(); //修改普通属性,看下会不会影响prototype alert(box1.name); //Lee box1.name = 'Rinima'; alert(box1.name); //Rinima alert(box2.name); //Lee,修改box1的普通属性,相当于直接在box1中添加一个属性,是不会牵扯到原型中的属性的。 //这一点非常好。但是如果是引用对象(数组)的话,就有问题了。 //修改引用属性,看下会不会影响prototype alert(box1.arr); //aaa,bbb box1.arr.push('ccc'); alert(box1.arr); //aaa,bbb,ccc alert(box2.arr); //aaa,bbb,ccc,修改box1的引用属性,却牵扯到了原型中的属性。 //这是因为arr只是个引用地址,指向数组真实存储的位置,修改box1中的引用属性就是修改引用所指向的数组,所以原型也被修改了 //这是我们不希望看到的!
Advantages of this mode:
1. The properties of the new object in the prototype are shared. At this time, box1.run == box2.run
2, it can ensure that the properties of the new object instance are completely unified. (Compared to Disadvantage 2)
Disadvantages of this mode:
1. When there is an attribute of a reference type, the attribute pointed to by the reference type does not exist. In the prototype, directly modifying the reference properties in the object will modify the reference properties of all objects
2. This mode omits the initialization parameter transfer, so that all properties of new are the same.
1.1. Prototype literal mode
(Another mode of prototype mode, generally there is not much difference, both belong to prototype mode)
function Box() {}; Box.prototype = { //使用字面量的方式 constructor : Box, name : 'Lee', age : 100, run : function () { return this.name + this.age + '运行中...'; } };
This mode inherits all the advantages and disadvantages of the prototype mode, but it also has its own unique advantages and disadvantages
Advantages: Better reflects the encapsulation
Disadvantages: The constructor does not point to itself and must be manually forced to point
2. Constructor + prototype mode
function Desk(name, age) { //不共享的使用构造函数 this.name = name; this.age = age; this.family = ['aaa', 'bbb', 'ccc']; }; Desk.prototype = { //共享的使用原型模式 constructor : Desk, run : function () { return this.name + this.age + this.family; } }; var desk1 = new Desk('Lee',100); var desk2 = new Desk('Jack',200); alert(desk1.family); //aaa,bbb,ccc desk1.family.push('ddd'); alert(desk1.family); //aaa,bbb,ccc,ddd alert(desk2.family); //aaa,bbb,ccc
Advantages: This mode It perfectly solves the problem of shared attributes and non-shared attributes, and can be precisely controlled. It is a very good model.
Disadvantages: However, in this method, the prototype and the constructor are separated, which makes people feel weird and does not reflect encapsulation.
3. Dynamic prototype mode
function Box(name ,age) { //将所有信息封装到函数体内 this.name = name; //不共享的属性 this.age = age; if (typeof this.arr != 'object') { //共享的属性 alert('在第一次调用的时候...arr'); Box.prototype.arr = ['aaa','bbb']; } if (typeof this.run != 'function') { alert('在第一次调用的时候...run'); Box.prototype.run = function () { return this.name + this.age + '运行中...'; }; } } var box1 = new Box(); var box2 = new Box(); alert( box1.arr ); //aaa,bbb box1.arr.push('ccc'); alert( box1.arr ); //aaa,bbb,ccc alert( box2.arr ); //aaa,bbb
Advantages: This mode inherits all the advantages of the previous mode (construction + prototype), and also perfectly solves the encapsulation problem
Note: Literal mode cannot be used when writing prototypes in this mode, which will cut off the connection between the instance and the new prototype. ? ? ?
At this point, the above two modes can already handle most problems, and they are better modes.
However, there are still some specific needs that require the use of the following two alternative modes.
4. Parasitic constructor pattern (factory pattern + constructor pattern)
function Box(name, age) { var obj = new Object(); obj.name = name; obj.age = age; obj.run = function () { return this.name + this.age + '运行中...'; }; return obj; }
5. Safe constructor pattern
function Box(name , age) { var obj = new Object(); obj.run = function () { return name + age + '运行中...'; //直接打印参数即可 }; return obj; }
Sure constructor mode is a mode that needs to be used when this is not allowed to be used in the constructor and new is not allowed to be used during external instantiation.
I don’t know why there is such a strange demand. However, so many object creation patterns are indeed much more dazzling than Java.
The above is the detailed content of Understand JavaScript object creation and object creation through prototypes. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest
