search
HomeWeb Front-endJS TutorialJavaScript custom types

JavaScript custom types

Nov 26, 2016 am 10:26 AM
javascript

In JavaScript, there are many modes for creating an object with custom properties and methods, which are introduced one by one below.
1. Create patterns directly. 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:


1 var person = new Object();
2 person.name = "Sam";
3 person.age = 16;
4 person.speak = function(){
5 alert(this. name + "is " + this.age + "years old");
6 }
7 person.speak();

You can see that an object of type Object is created above, and then name and age are added to it Properties and a speak method. 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. Factory pattern is a commonly used design pattern in programming. It mainly encapsulates the process of creating objects. The sample code is as follows:


1 function createPerson(name, age){
2 var person = new Object() ;
3 person.name = name;
4 person.age = age;
5 person.speak = function(){
6 alert(this.name + "is " + this.age + "years old");
7 }
8 return person;
9 }
10 var person1 = createPerson("Sam", 16);
11 var person2 = createPerson("Jack", 18);

After using the factory pattern, create objects of the same type It becomes 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:


1 function Person(name, age){
2 this.name = name;
3 this.age = age;
4 this.speak = function(){
5 alert(this.name + "is " + this.age + "years old");
6 }
7 }
8 var person1 = new Person("Sam", 16);
9 var person2 = new Person("Jack", 18);

You can see that 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.

1 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:


1 function Person( name, age){
2 this.name = name;
3 this.age = age;
4 this.speak = speak;
5 }
6 function speak(){
7 alert(this.name + "is " + this.age + "years old");
8 }
9 var person1 = new Person("Sam", 16);
10 var person2 = new Person("Jack", 18);
11 alert(person1. speak == person2.speak); // true

The problem is solved, but this method brings 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:


1 function Person(){}
2 Person.prototype.name="Sam";
3 Person.prototype.age=16;
4 Person.prototype.speak = function(){
5 alert(this.name + "is " + this.age + "years old");
6 }
7 var person1 = new Person();
8 person1.speak();
9 var person2 = new Person() ;
10 alert(person1.speak == person2.speak); // true

You can see that 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, first search instance attributes and methods, and return if found; if not found, search again in prototype. 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:


1 function Person(name, age){
2 this.name = name;
3 this.age = age;
4 }
5 Person.prototype.speak = function(){
6 alert (this.name + "is " + this.age + "years old");
7 }
8 var person1 = new Person();
9 person1.speak();
10 var person2 = new Person();
11 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:


1 function Person(name, age){
2 this.name = name;
3 this.age = age;
4 if (Person.prototype.speak == "undefined"){
5 Person.prototype.speak = function(){
6 alert(this.name + "is " + this.age + "years old");
7 }
8 }
9 }


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
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

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

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft