search
HomeWeb Front-endJS TutorialDetailed explanation of object model code for JavaScript custom properties and methods

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();

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);

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);

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

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

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

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"); 
} 
} 
}


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
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment