Table of Contents
1. Factory pattern" >1. Factory pattern
2. Constructor mode" >2. Constructor mode
3. Prototype mode" >3. Prototype mode
四、组合使用构造函数模式和原型模式" >四、组合使用构造函数模式和原型模式
五、动态原型模式" >五、动态原型模式
六、寄生构造函数模式" >六、寄生构造函数模式
七、稳妥构造函数模式" >七、稳妥构造函数模式
Home Web Front-end JS Tutorial 7 classic ways to create objects in JavaScript (summary)

7 classic ways to create objects in JavaScript (summary)

Jan 11, 2021 pm 06:25 PM
javascript Create object

7 classic ways to create objects in JavaScript (summary)

Related recommendations: "javascript video tutorial"

There are many ways to create objects in JavaScript, through the Object constructor or object literal. You can also create a single object. Obviously, these two methods will generate a lot of repeated code and are not suitable for mass production. Next, we will introduce seven very classic ways to create objects. They each have their own advantages and disadvantages. (The content mainly comes from "JavaScript Advanced Programming", and also refers to articles written by others)

1. Factory pattern

function createPerson(name, job) { 
 var o = new Object();
 o.name = name;
 o.job = job;
 o.sayName = function() { 
  console.log(this.name); 
 } 
 return o 
} 
var person1 = createPerson('Mike', 'student') 
var person2 = createPerson('X', 'engineer')
Copy after login

This factory function can be called an unlimited number of times, and each time it returns an object containing two properties and a method.

Although the factory pattern solves the problem of creating multiple similar objects, it does not solve the problem of object identification, that is, it cannot know the type of an object.

2. Constructor mode

function Person(name, job) { 
 this.name = name;
 this.job = job;
 this.sayName = function() { 
  console.log(this.name);
 } 
} 
var person1 = new Person('Mike', 'student') 
var person2 = new Person('X', 'engineer')
Copy after login

There is no displayed object to create. Use new to call this constructor. After using new, it will be executed automatically. The following operations:

① Create a new object;

② Assign the scope of the constructor to the new object (so this points to this new object);

③ Execute the code in the constructor (add properties to this new object);

④Return the new object.

Disadvantages: Each method must be recreated on each instance.

It is not necessary to create two Function instances that complete the same task. Moreover, with this object, there is no need to bind the function to a specific object before executing the code. It can be defined in this form:

function Person( name, age, job ){
    this.name = name;
    this.age = age;
    this.job = job;
    this.sayName = sayName;
}
function sayName(){
    alert( this.name );
}
Copy after login

In this way, the definition of the sayName() function can be Move outside the constructor. Inside the constructor, we set the sayName property to the global sayName function. In this case, since sayName contains a pointer to a function, the person1 and person2 objects can share the same sayName() function defined in the global scope.

This solves the problem of two functions doing the same thing, but a new problem arises: a function defined in the global scope can actually only be called by a certain object, which makes the global scope The domain is a bit of a misnomer. And more importantly: if the object needs to define many methods, then many global functions need to be defined. In this way, our customized reference type has no encapsulation at all.

These problems can be solved by using the prototype pattern.

3. Prototype mode

function Person() { 
} 
Person.prototype.name = 'Mike' 
Person.prototype.job = 'student' 
Person.prototype.sayName = function() { 
 console.log(this.name) 
} 
var person1 = new Person()
Copy after login

Add information directly to the prototype object. The advantage of using a prototype is that all instance objects can share the properties and methods it contains. Instead of defining object instance information in the constructor, this information can be added directly to the prototype object.

①Understand the prototype

Whenever a new function is created, a prototype attribute will be created for the function according to a specific set of rules.

By default, all prototype properties will automatically obtain a constructor (constructor) attribute, which contains a pointer to the function where the prototype attribute is located.

Every time the code reads a property of an object, a search is performed, targeting the property with the given name. The search starts with the object instance itself. If an attribute with the given name is found in the instance, the value of the attribute is returned; if not found, the prototype object pointed to by the pointer is searched and the attribute with the given name is found in the prototype object. If this property is found in the prototype object, the value of this property is returned.

Although the value stored in the prototype can be accessed through the object instance, the value in the prototype cannot be overwritten through the object instance.

If we add a property to the instance, and the property has the same name as a property in the instance, then the property will be created in the instance, and the property will mask that property in the prototype.

Even if the property is set to null, only the property value in the instance is null.

However, using the delete operator can completely delete instance properties, allowing you to re-access the properties in the prototype.

Use the hasOwnProperty() method to detect whether a property exists in the instance or in the prototype. This method will return true only if the given property exists in the object instance.

②Prototype and in operator

The in operator will return true when a given property can be accessed through the object, regardless of whether the property exists in the instance or the prototype middle.

③Simpler prototype syntax

function Person(){    
}
Person.prototype = {
    name : "Mike",
    age : 29,
    job : "engineer",    
    syaName : function(){
        alert( this.name );
    }
};
Copy after login

In the above code, Person.prototype is set equal to a new object created in the form of an object literal. The end result is the same, with one exception: the constructor property no longer points to the Person.

四、组合使用构造函数模式和原型模式

组合使用构造函数模式和原型模式是使用最为广泛、认同度最高的一种创建自定义类型的方法。它可以解决上面那些模式的缺点,使用此模式可以让每个实例都会有自己的一份实例属性副本,但同时又共享着对方法的引用,这样的话,即使实例属性修改引用类型的值,也不会影响其他实例的属性值了。还支持向构造函数传递参数,可谓是集两种模式的优点。

function Person(name) { 
 this.name = name; 
 this.friends = ['Jack', 'Merry']; 
} 
Person.prototype.sayName = function() { 
 console.log(this.name); 
} 
var person1 = new Person(); 
var person2 = new Person(); 
person1.friends.push('Van'); 
console.log(person1.friends) //["Jack", "Merry", "Van"] 
console.log(person2.friends) // ["Jack", "Merry"] 
console.log(person1.friends === person2.friends) //false
Copy after login

五、动态原型模式

动态原型模式将所有信息都封装在了构造函数中,初始化的时候。可以通过检测某个应该存在的方法是否有效,来决定是否需要初始化原型。

function Person(name, job) { 
  // 属性 
 this.name = name;
 this.job = job;
 // 方法 
 if(typeof this.sayName !== 'function') { 
  Person.prototype.sayName = function() { 
    console.log(this.name) 
  } 
 } 
} 
var person1 = new Person('Mike', 'Student') 
person1.sayName()
Copy after login

只有在sayName方法不存在的时候,才会将它添加到原型中。这段代码只会初次调用构造函数的时候才会执行。此后原型已经完成初始化,不需要在做什么修改了,这里对原型所做的修改,能够立即在所有实例中得到反映。

其次,if语句检查的可以是初始化之后应该存在的任何属性或方法,所以不必用一大堆的if语句检查每一个属性和方法,只要检查一个就行。

六、寄生构造函数模式

这种模式的基本思想就是创建一个函数,该函数的作用仅仅是封装创建对象的代码,然后再返回新建的对象

function Person(name, job) { 
  var o = new Object();
 o.name = name;
 o.job = job;
 o.sayName = function() { 
  console.log(this.name) 
 } 
 return o 
} 
var person1 = new Person('Mike', 'student') 
person1.sayName()
Copy after login

这个模式,除了使用new操作符并把使用的包装函数叫做构造函数之外,和工厂模式几乎一样。

构造函数如果不返回对象,默认也会返回一个新的对象,通过在构造函数的末尾添加一个return语句,可以重写调用构造函数时返回的值。

七、稳妥构造函数模式

首先明白稳妥对象指的是没有公共属性,而且其方法也不引用this。稳妥对象最适合在一些安全环境中(这些环境会禁止使用this和new),或防止数据被其他应用程序改动时使用。

稳妥构造函数模式和寄生模式类似,有两点不同:1.是创建对象的实例方法不引用this;2.不使用new操作符调用构造函数

function Person(name, job) { 
 var o = new Object();
 o.name = name;
 o.job = job;
 o.sayName = function() { 
  console.log(name) //注意这里没有了"this";
 } 
 return o 
} 
var person1 = Person('Mike', 'student') 
person1.sayName();
Copy after login

和寄生构造函数模式一样,这样创建出来的对象与构造函数之间没有什么关系,instanceof操作符对他们没有意义

更多编程相关知识,请访问:编程学习!!

The above is the detailed content of 7 classic ways to create objects in JavaScript (summary). 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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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 solve the problem that activex components cannot create objects How to solve the problem that activex components cannot create objects Jan 24, 2024 pm 02:48 PM

Solution: 1. Check spelling and path; 2. Add reference to component; 3. Check registry; 4. Run as administrator; 5. Update or repair Office; 6. Check security software; 7. Use other versions Components; 8. View error messages; 9. Find other solutions. Detailed introduction: 1. Check spelling and path: Make sure there are no spelling errors in the name and path of the object, and the file does exist in the specified path; 2. Add references to components, etc.

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

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.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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

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

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles