Home Web Front-end JS Tutorial Detailed explanation of object model code for JavaScript custom properties and methods

Detailed explanation of object model code for JavaScript custom properties and methods

Jul 21, 2017 pm 04:12 PM
javascript js customize

In JavaScript, there are many modes for creating an object with custom properties and methods

1. Direct creation mode. This is the simplest and most straightforward pattern. First create an object of reference type and then add custom properties and methods to it. The sample code is as follows:

var person = new Object(); 
person.name = "Sam"; 
person.age = 16; 
person.speak = function(){ 
alert(this.name + "is " + this.age + "years old"); 
} 
person.speak();
Copy after login

As you can see, an object of type Object is created above, and then the name and age attributes and a speak method are added to it. Although creating a pattern directly is simple, its disadvantage is obvious: when we need to create many identical objects, we have to write code repeatedly every time. In order to solve this problem, we can encapsulate the process of creating objects, so we have the following factory pattern.
2. Factory mode. The factory pattern is a commonly used design pattern in programming. It mainly encapsulates the process of creating objects. The sample code is as follows:

function createPerson(name, age){ 
var person = new Object(); 
person.name = name; 
person.age = age; 
person.speak = function(){ 
alert(this.name + "is " + this.age + "years old"); 
} 
return person; 
} 
var person1 = createPerson("Sam", 16); 
var person2 = createPerson("Jack", 18);
Copy after login

After using the factory pattern, creating objects of the same type changes Gotta be simple. But the factory pattern does not solve the problem of object identification, that is, we cannot determine the specific type of the object created. Developers who have experience in object-oriented programming all know that the creation of objects should be based on classes. Once you have a specific custom class, you can then create objects of that class. Fortunately, in JavaScript, we can simulate a class through the constructor pattern.
3. Constructor pattern. There is no difference between constructors and ordinary functions. Any ordinary function can be used as a constructor, as long as the new operator is used; any constructor can also be called as an ordinary function. But in JavaScript, there is a convention that the function name used as a constructor needs to have the first letter capitalized. The sample code is as follows:

function Person(name, age){ 
this.name = name; 
this.age = age; 
this.speak = function(){ 
alert(this.name + "is " + this.age + "years old"); 
} 
} 
var person1 = new Person("Sam", 16); 
var person2 = new Person("Jack", 18);
Copy after login

As you can see, inside the constructor, we use this to add properties and methods. So, what does this refer to? When we create a Person object, this refers to the created object. Now, we can identify the specific types of objects person1 and person2. After using alert(person1 instanceOf Person), you can find that the output value is true. But the constructor pattern also has its own shortcomings, that is, the methods declared within the constructor will be recreated every time a new object is created (in JavaScript, functions are also objects). In other words, the methods within the constructor are bound to the object, not to the class. The output of the code below can verify our inference.
alert(person1.speak == person2.speak); // false A relatively simple way to solve this shortcoming is to put the function declaration outside the constructor, that is:

function Person(name, age){ 
this.name = name; 
this.age = age; 
this.speak = speak; 
} 
function speak(){ 
alert(this.name + "is " + this.age + "years old"); 
} 
var person1 = new Person("Sam", 16); 
var person2 = new Person("Jack", 18); 
alert(person1.speak == person2.speak); // true
Copy after login

Problem Solved, but this method brought new problems. First, the function speak is declared in the global scope, but it can only be used in the Person constructor. There is a risk of misuse when placed in the global scope; secondly, if a custom type has many methods, Then you need to declare a lot of global functions, which will not only lead to pollution of the global scope, but also is not conducive to code encapsulation. So, is there any way to make a custom type method bound to a class without polluting the global scope? The answer is to use prototype pattern.
4. Prototype mode. After we declare a new function, the function (in JavaScript, functions are also objects) will have a prototype attribute. A prototype is an object that represents the public properties and methods owned by all objects created by this function. The sample code is as follows:

function Person(){} 
Person.prototype.name="Sam"; 
Person.prototype.age=16; 
Person.prototype.speak = function(){ 
alert(this.name + "is " + this.age + "years old"); 
} 
var person1 = new Person(); 
person1.speak(); 
var person2 = new Person(); 
alert(person1.speak == person2.speak); // true
Copy after login

As you can see, although the speak method is not declared in the constructor, the object person1 we created can still call the speak method. This is because JavaScript has a search rule, search first Instance attributes and methods are returned if found; if not found, search in prototype again. The prototype pattern makes the method related to the class and does not pollute the global scope, but it also has its own shortcomings: First, all attributes are also related to the class, which means that all objects share one attribute, which is obviously unreasonable. ; Second, there is no way to pass initialization data to the constructor. The solution is simple, just use a mix of constructor pattern and prototype pattern.
5. Combination mode. The sample code is as follows:

function Person(name, age){ 
this.name = name; 
this.age = age; 
} 
Person.prototype.speak = function(){ 
alert(this.name + "is " + this.age + "years old"); 
} 
var person1 = new Person(); 
person1.speak(); 
var person2 = new Person(); 
alert(person1.speak == person2.speak); // true
Copy after login

It is not difficult to find that the combination mode meets all our needs, and it is also a mode that is currently widely used. Developers with experience in object-oriented programming may feel that it is a bit awkward to put the prototype declaration outside the constructor, so can it be put into the constructor? The answer is yes, just use dynamic combination mode.
6. Dynamic combination mode. The principle is to first determine whether a certain attribute or method in the prototype has been declared. If not, declare the entire prototype; otherwise, do nothing. The sample code is as follows:

function Person(name, age){ 
this.name = name; 
this.age = age; 
if (Person.prototype.speak == "undefined"){ 
Person.prototype.speak = function(){ 
alert(this.name + "is " + this.age + "years old"); 
} 
} 
}
Copy after login


The above is the detailed content of Detailed explanation of object model code for JavaScript custom properties and methods. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to quickly set up a custom avatar in Netflix How to quickly set up a custom avatar in Netflix Feb 19, 2024 pm 06:33 PM

An avatar on Netflix is ​​a visual representation of your streaming identity. Users can go beyond the default avatar to express their personality. Continue reading this article to learn how to set a custom profile picture in the Netflix app. How to quickly set a custom avatar in Netflix In Netflix, there is no built-in feature to set a profile picture. However, you can do this by installing the Netflix extension on your browser. First, install a custom profile picture for the Netflix extension on your browser. You can buy it in the Chrome store. After installing the extension, open Netflix on your browser and log into your account. Navigate to your profile in the upper right corner and click

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

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

How to customize shortcut key settings in Eclipse How to customize shortcut key settings in Eclipse Jan 28, 2024 am 10:01 AM

How to customize shortcut key settings in Eclipse? As a developer, mastering shortcut keys is one of the keys to improving efficiency when coding in Eclipse. As a powerful integrated development environment, Eclipse not only provides many default shortcut keys, but also allows users to customize them according to their own preferences. This article will introduce how to customize shortcut key settings in Eclipse and give specific code examples. Open Eclipse First, open Eclipse and enter

The operation process of edius custom screen layout The operation process of edius custom screen layout Mar 27, 2024 pm 06:50 PM

1. The picture below is the default screen layout of edius. The default EDIUS window layout is a horizontal layout. Therefore, in a single-monitor environment, many windows overlap and the preview window is in single-window mode. 2. You can enable [Dual Window Mode] through the [View] menu bar to make the preview window display the playback window and recording window at the same time. 3. You can restore the default screen layout through [View menu bar>Window Layout>General]. In addition, you can also customize the layout that suits you and save it as a commonly used screen layout: drag the window to a layout that suits you, then click [View > Window Layout > Save Current Layout > New], and in the pop-up [Save Current Layout] Layout] enter the layout name in the small window and click OK

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

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

How to customize x-axis and y-axis in excel? (How to customize excel axis scale) How to customize x-axis and y-axis in excel? (How to customize excel axis scale) Mar 14, 2024 pm 02:10 PM

In an excel table, sometimes you may need to insert coordinate axes to see the changing trend of the data more intuitively. Some friends still don’t know how to insert coordinate axes in the table. Next, I will share with you how to customize the coordinate axis scale in Excel. Coordinate axis insertion method: 1. In the excel interface, select the data. 2. In the insertion interface, click to insert a column chart or bar chart. 3. In the expanded interface, select the graphic type. 4. In the right-click interface of the table, click Select Data. 5. In the expanded interface, you can customize it.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

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.

See all articles