


A brief discussion on factory functions and constructors in JavaScript
When it comes to the JavaScript language compared to other programming languages, you may hear some confusing things, one of which is factory functions and constructors.
Factory function
The so-called Factory function means that these built-in functions are class objects. When you call them, "A class instance is actually created". This means that when I call this function, I actually create an object using the class and then return the object. Since Javascript itself is not a strict object-oriented language (does not contain classes), Actually, Javascript does not have a strict "factory function", but in Javascript, we can use functions to simulate classes. Let's look at the following example:
function person(firstName, lastName, age) { const person = {}; person.firstName = firstName; person.lastName = lastName; person.age = age; return person; }
The above code creates a new object and passes it The parameters are attached to the object as properties and the new object is returned. This is a simple JavaScript factory function.
In fact, the factory function is also easy to understand:
It is a function.
It is used to create objects.
It is like a factory, "produced" The functions are all "standard parts" (have the same attributes)
Constructor
Different from other mainstream programming languages, JavaScript The constructor does not exist as a specific method of the class; when any ordinary function is used to create a class of objects, it is called a constructor, or constructor. For a function to be a true constructor, The following conditions need to be met:
Set the properties of the new object (this) inside the function, usually by adding properties and methods.
The constructor can contain a return statement (not recommended), but the return value must be this, or other non-object type value.
function Person(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; }
Use the new keyword to create an object
As mentioned above, we can use new
to classes or objects, then you may have the following questions:
- We can Is the
new
keyword used in the factory function? - What happens if we use the
new
keyword in the factory and constructor? - If in What happens when you create an object instance using a constructor without using the new keyword
Okay, before trying to find out the answer to the above question, let’s do a small exercise to understand what’s going on here .
Use the new
keyword to create two objects using the factory and constructor at the same time, and then print the two objects on the console.
Use the factory function
function person(firstName, lastName, age){ const person = {} person.firstName = firstName; person.lastName = lastName; person.age = age; return person; } const mike = new person('mike', 'grand', 23);
As we have seen above, here __proto__
is a pointer to its prototype object, let us try to find out What is the prototype object. In order to find out the prototype object pointed to by the mike
object above, let's do a simple ===
equality check.
Well, interestingly, it points to Object.prototype
. Okay, let's do the same experiment with the constructor.
Understanding the prototype of JavaScript
Before understanding the prototype, you need to remember the following knowledge:
- All reference types (arrays, Objects, functions), all have object characteristics, which can be freely extended attributes (except null)
- All reference types (arrays, objects, functions) have a __proto__ attribute, and the attribute value is an ordinary Object
- All functions have a prototype attribute, and the attribute value is also an ordinary object
- For all reference types (arrays, objects, functions), the __proto__ attribute value points to it The prototype attribute value of the constructor
Explain it through the code:
// 要点一:自由扩展属性 var obj = {}; obj.a = 100; var arr = []; arr.a = 100; function fn () {} fn.a = 100; // 要点二:__proto__ console.log(obj.__proto__); console.log(arr.__proto__); console.log(fn.__proto__); // 要点三:函数有 prototype console.log(fn.prototype) // 要点四:引用类型的 __proto__ 属性值指向它的构造函数的 prototype 属性值 console.log(obj.__proto__ === Object.prototype)
Using the constructor
Note: In JavaScript, these constructs Functions are also called constructor because they are used to create objects.
function Person(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } const mike = new Person('mike', 'grand', 23);
When we expand the __proto__
of the first layer, there is another __proto__
inside it, we expand it again it.
Now let’s try to figure out if the prototype object looks like above.
他们是不同的。 当我们使用工厂函数创建对象时,它的__proto__
指向Object.prototype
,而当从构造函数创建对象时,它指向它的构造函数原型对象。 那么这里发生了什么?
new 背后所做的事
当我们在创建对象时使用带有构造函数的new
关键字时,new
背后所做的事不多。
new 运算符创建一个用户自定义的对象类型的实例或具有构造函数的内置对象的实例。 new 关键字会进行如下操作:
- 创建一个空的简单 JavaScript 对象 (即 {})
- 链接该对象(即设置该对象的构造函数)到另一个对象
- 将步骤1新创建的对象作为 this 的上下文
- 如果该函数没有返回对象,则返回 this
注释行是伪代码,表示在 new 关键字,JS 背后帮我们做的事情。
function Person(firstName, lastName, age) { // this = {}; // this.__proto__ = Person.prototype; this.firstName = firstName; this.lastName = lastName; this.age = age; // return this; }
另外,让我们看看如果将上面的隐式代码添加到工厂函数中会发生什么。
function person(firstName, lastName, age) { // this = {}; // this.__proto__ = Person.prototype; const person = {}; person.firstName = firstName; person.lastName = lastName; person.age = age; return person; // return this; }
即使使用new
关键字调用时将隐式代码添加到工厂函数中,也不会对结果产生任何影响。这是因为,由于我们没有在函数中使用 this 关键字,而且我们显式地返回了一个除this之外的自定义对象,因此没有必要使用隐式代码。无论我们是否对工厂函数使用new关键字,对输出都没有影响。
如果忘记了 new 关键字怎么办
JavaScript 中有许多概念,有时难以掌握。 new
操作符就是其中之一。 如果你不能正确理解它,那么在运行 JavaScript 应用程序时会产生令人讨厌的后果。 在像 Java这 样的语言中,严格限制了如何使用 new
关键字。 但是在 javascript 中,并不是那么严格,如果你不能正确理解它们可能会导致很多问题。
在 JavaScript 中:
- 可以对任何函数使用
new
运算符 - 可以使用或不使用
new
关键字将函数作为构造函数调用
让我们看看上面的例子,使用和不使用 new
关键情况
function Person(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } const mike = new Person('mike', 'grand', 23); const bob = Person('bob', 'grand', 23);
然后,如果查看创建的对象实例,你希望看到什么?
发生了什么? 使用 new
运算符,正如我们所期待的一样输出正确的对象,但没有new
运算符,结果是undefined
怎么可能呢?
如果你对 JavaScript 作用域 和 this
关键字的工作原理有所了解,那么你可以猜到这里发生了什么? 让我们来看看。
看起来我们传递给没有new
关键字的函数的所有属性都已设置为window
对象。 那是因为到那个时候函数内部的这个变量引用了global 或 window
对象,基本上我们在这里做的就是污染了全局对象。
这是你可以对你的JavaScript程序做的非常讨厌的事情。 因此,使用new
运算符,JavaScript引擎将this
变量设置为引用新创建的对象实例,这就是为什么我们可以看到传递给构造函数的所有属性都已设置为 mike
。
但是在没有new
运算符的情况下调用构造函数的情况下,JavaScript 引擎会将 this
解释为常规函数调用,而没有显式返回语句时返回undefined
。 这就是理解new
运算符在JavaScript中的工作原理非常关键的原因。
原文地址:https://medium.com/@chamikakasun/javascript-factory-functions-vs-constructor-functions-585919818afe
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of A brief discussion on factory functions and constructors in JavaScript. 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











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

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

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.

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

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

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
