


Detailed explanation of usage of defining class instances in JavaScript through functions
Let’s first illustrate with an example:
function myClass() { var id = 1; var name = "johnson"; //properties this.ID = id; this.Name = name; //method this.showMessage = function() { alert("ID: " + this.ID + ", Name: " + this.Name); } } var obj1 = new myClass(); var obj2 = new myClass();
The definition of function is actually equivalent to the constructor of the class, and the last two sentences are to create an instance of this class. Let’s analyze the first sentence first: var obj1 = new myClass(); When using new to create an instance of a class, the interpreter will first create an empty object. Then run this myClass function and point this pointer to an instance of this class. When encountering this.ID = id; and this.Name = name; and this.showMessage = function(){...}, these two properties and this method will be created, and the variables id and name will be The definition of the value-level function is assigned to these two properties and this function object (shwoMessage). This process is equivalent to initializing the object, similar to the constructor in C#. Finally new returns this object. Look at the second sentence: var obj2 = new myClass(); The execution process is the same as the previous sentence, that is, creating an empty object, then executing the myClass function and defining two properties and a method.
As can be seen from the above analysis, the above way of implementing a class is to define the attribute method of the class in the definition of the function. There are disadvantages. If two or more instances of this class need to be created, as shown above, these properties will be created multiple times.
So how to avoid this situation? Prototype is a prototype like its name. Each function has a sub-object prototype, which actually represents the collection of members of this function object. Since here we use functions to implement classes, we can say that prototype is actually the class. A collection of members. The properties and methods defined by the prototype are executed before the function's constructor is executed, so before an object is new, the members of the prototype have actually been executed. Let’s look at an example first: The structure of the
function myClass() { //构造函数 } myClass.prototype = { ID: 1, Name: "johnson", showMessage: function() { alert("ID: " + this.ID + ", Name: " + this.Name); } } var obj1 = new myClass(); var obj2 = new myClass();
class is still the same as the previous example, but here it is implemented using prototype. Let’s look at the last two sentences first. As mentioned before, prototype is executed before the function constructor, that is, before var obj1 = new myClass(); is executed, this class already has an ID, Name attribute and showMessage method. The execution process of the executor is as follows. Note the comparison with the previous example: first, create an empty object and point the this pointer to this object. Then assign all members of the function's prototype object to this object (note that these members are not created again). Then execute the function body. Finally new returns this object. When executing the next sentence: This process is also executed and these members will not be created repeatedly.
The above code is just an example. In actual projects, there may be a large number of members in the class, and a large number of instances may need to be created. This prototype will show its superiority. In addition, the above code uses brace syntax to define members of the prototype, so that the code looks clearer. This is a recommended class design pattern. Of course, in many projects, we may find better models. We also hope to have more optimized JavaScript programming models to continue to introduce new ones. We also hope that as time goes by, all mainstream browsers will also standardize JavaScript parsing. ,Unite.
As mentioned above, the members defined by prototype occur before the constructor. It can be proved that in the above example, the constructor is empty. Add an alert(this.Name); to the constructor. When the execution reaches When var obj1 = new myClass();, you will see a pop-up dialog box showing the correct attribute values.
The following code:
function subClass(){ } subClass.prototype = { Name: "sub" } function myClass() { //构造函数 } myClass.prototype = { ID: 1, Name: "johnson", SubObj: new subClass(), showMessage: function() { alert("ID: " + this.ID + ", Name: " + this.Name + "SubObj.Name:" + this.SubObj.Name); } } var obj1 = new myClass(); obj1.SubObj.Name = "XXX"; obj1.showMessage(); var obj2 = new myClass(); obj2.showMessage();
Here a reference type is defined in myClass, its type is a subClass class we customized, and there is a Name attribute in this subclass. Since the prototype object is shared, according to our analysis above: when executing var obj1 = new myClass();, the members of the prototype of myClass will be copied to this obj1 instance. But SubObj here is a reference type. When var obj2 = new myClass(); is executed, the ID and Name members in the prototype will be copied to obj2, but the SubObj attribute will not be copied, but will refer to the prototype. SubObj, so because the previous sentence modified the value of obj1.Subobj.Name, when using new to generate an obj2 instance, the modified value is referenced.
So when you use prototype to define a class, you still need to define the attributes in the constructor and define the methods on the prototype of the constructor. As follows:
function myClass(id, name) { this.ID = id; this.Name = name; } myClass.prototype = { showMessage: function() { alert("ID: " + this.ID + ", Name: " + this.Name); }, showMessage2: function() { alert("Method2"); } } var obj1 = new myClass(1, "johnson"); obj1.showMessage(); obj1.Name="John"; obj1.showMessage(); var obj2 = new myClass(2, "Amanda"); obj2.showMessage();
The above is the detailed content of Detailed explanation of usage of defining class instances in JavaScript through functions. 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



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

The composite primary key in MySQL refers to the primary key composed of multiple fields in the table, which is used to uniquely identify each record. Unlike a single primary key, a composite primary key is formed by combining the values of multiple fields. When creating a table, you can define a composite primary key by specifying multiple fields as primary keys. In order to demonstrate the definition and function of composite primary keys, we first create a table named users, which contains three fields: id, username and email, where id is an auto-incrementing primary key and user

"Exploring Discuz: Definition, Functions and Code Examples" With the rapid development of the Internet, community forums have become an important platform for people to obtain information and exchange opinions. Among the many community forum systems, Discuz, as a well-known open source forum software in China, is favored by the majority of website developers and administrators. So, what is Discuz? What functions does it have, and how can it help our website? This article will introduce Discuz in detail and attach specific code examples to help readers learn more about it.

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

Introduction to PHP interface and how it is defined. PHP is an open source scripting language widely used in Web development. It is flexible, simple, and powerful. In PHP, an interface is a tool that defines common methods between multiple classes, achieving polymorphism and making code more flexible and reusable. This article will introduce the concept of PHP interfaces and how to define them, and provide specific code examples to demonstrate their usage. 1. PHP interface concept Interface plays an important role in object-oriented programming, defining the class application

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

What are full-width characters? In computer encoding systems, double-width characters are a character encoding method that takes up two standard character positions. Correspondingly, the character encoding method that occupies a standard character position is called a half-width character. Full-width characters are usually used for input, display and printing of Chinese, Japanese, Korean and other Asian characters. In Chinese input methods and text editing, the usage scenarios of full-width characters and half-width characters are different. Use of full-width characters Chinese input method: In the Chinese input method, full-width characters are usually used to input Chinese characters, such as Chinese characters, symbols, etc.
