Table of Contents
Constructors and operators "new"
Constructor
new function() { ... }
Constructor pattern test: new.target
Constructor's return
Omit brackets
Methods in constructors
总结
作业题
1. 两个函数 — 一个对象
2. 创建 new Calculator
3. 创建 new Accumulator
Home Web Front-end JS Tutorial Detailed explanation of JavaScript constructor and 'new' operator

Detailed explanation of JavaScript constructor and 'new' operator

Nov 13, 2020 pm 05:39 PM

javascriptThe column introduces the "new" operator.

Detailed explanation of JavaScript constructor and 'new' operator

Constructors and operators "new"

The regular {...} syntax allows creation of an object. But we often need to create many similar objects, such as multiple users or menu items, etc.

This can be achieved using constructors and the "new" operator.

Constructor

Constructor is technically a regular function. But there are two conventions:

  1. Their names start with a capital letter.
  2. They can only be executed by the "new" operator.

For example:

function User(name) {  this.name = name;  this.isAdmin = false;
}let user = new User("Jack");

alert(user.name); // Jackalert(user.isAdmin); // false复制代码
Copy after login

When a function is executed using the new operator, it follows the following steps:

  1. a A new empty object is created and assigned to this.
  2. Function body execution. Usually it will modify this, adding new properties to it.
  3. Returns the value of this.

In other words, new User(...) does something like:

function User(name) {  // this = {};(隐式创建)

  // 添加属性到 this
  this.name = name;  this.isAdmin = false;  // return this;(隐式返回)}复制代码
Copy after login

So new User("Jack" ) results in the same object:

let user = {  name: "Jack",  isAdmin: false};复制代码
Copy after login

Now, if we want to create other users, we can call new User("Ann"),new User( "Alice") etc. Much shorter and easier to read than using literal creation every time.

This is the main purpose of the constructor - to implement reusable object creation code.

Let us stress it again - technically any function can be used as a constructor. That is: any function can be run through new, which will execute the above algorithm. "Capitalization" is a common convention to make it clear that a function will be run using new.

new function() { ... }

If we have many lines of code that create a single complex object, we can encapsulate them in a constructor, like this:

let user = new function() {  this.name = "John";  this.isAdmin = false;  // ……用于用户创建的其他代码
  // 也许是复杂的逻辑和语句
  // 局部变量等};复制代码
Copy after login

The constructor cannot be called again because it is not saved anywhere, just created and called. Therefore, this tip is intended to encapsulate the code that builds a single object without needing to reuse it in the future.

Constructor pattern test: new.target

Advanced content:

The syntax content involved in this section is rarely used unless You want to understand everything, otherwise you can just skip the syntax.

Inside a function, we can use the new.target property to check whether it has been called using new.

For regular calls, it is empty. For calls using new, it is equal to the function:

function User() {
  alert(new.target);
}// 不带 "new":User(); // undefined// 带 "new":new User(); // function User { ... }复制代码
Copy after login

It can be used inside the function to determine the function Is it the "constructor mode" that is called through new, or the "regular mode" that is not called through new.

We can also make the new call do the same job as a regular call, like this:

function User(name) {  if (!new.target) { // 如果你没有通过 new 运行我
    return new User(name); // ……我会给你添加 new
  }  this.name = name;
}let john = User("John"); // 将调用重定向到新用户alert(john.name); // John复制代码
Copy after login

This approach is sometimes used in libraries to make the syntax more flexible . In this way, when people call the function, the program will work regardless of whether new is used.

It's not a good thing to use it everywhere, though, because omitting new makes it difficult to observe what's going on in the code. And through new we can all know that this creates a new object.

Constructor's return

Normally, a constructor does not have a return statement. Their job is to write all the necessary stuff into this and automatically convert it into the result.

However, if there is a return statement, then the rule is simple:

  • If return returns an object, Then return this object instead of this.
  • If return returns a primitive type, it is ignored.

In other words, return with an object returns that object, in all other cases this is returned.

For example, here return overrides this by returning an object:

function BigUser() {  this.name = "John";  return { name: "Godzilla" };  // <-- 返回这个对象}

alert( new BigUser().name );  // Godzilla,得到了那个对象复制代码
Copy after login

Here is an example where return is empty (Or we could put a primitive type after it, no effect):

function SmallUser() {  this.name = "John";  return; // <-- 返回 this}

alert( new SmallUser().name );  // John复制代码
Copy after login

Normally constructors don't have a return statement. Here we mention the special behavior of returned objects mainly for completeness.

Omit brackets

By the way, if there are no parameters, we can omit the brackets after new:

let user = new User; // <-- 没有参数// 等同于let user = new User();复制代码
Copy after login

Omitting brackets here is not considered A "good style", but the syntax is allowed by the specification.

Methods in constructors

Using constructors to create objects brings great flexibility. A constructor may have parameters that define how the object is constructed and what to put in it.

当然,我们不仅可以将属性添加到 this 中,还可以添加方法。

例如,下面的 new User(name) 用给定的 name 和方法 sayHi 创建了一个对象:

function User(name) {  this.name = name;  this.sayHi = function() {
    alert( "My name is: " + this.name );
  };
}let john = new User("John");

john.sayHi(); // My name is: John/*
john = {
   name: "John",
   sayHi: function() { ... }
}
*/复制代码
Copy after login

类 是用于创建复杂对象的一个更高级的语法,我们稍后会讲到。

总结

  • 构造函数,或简称构造器,就是常规函数,但大家对于构造器有个共同的约定,就是其命名首字母要大写。
  • 构造函数只能使用 new 来调用。这样的调用意味着在开始时创建了空的 this,并在最后返回填充了值的 this

我们可以使用构造函数来创建多个类似的对象。

JavaScript 为许多内置的对象提供了构造函数:比如日期 Date、集合 Set 以及其他我们计划学习的内容。

对象,我们还会回来哒!

在本章中,我们只介绍了关于对象和构造器的基础知识。它们对于我们在下一章中,学习更多关于数据类型和函数的相关知识非常重要。

在我们学习了那些之后,我们将回到对象,在 info:prototypes 和 info:classes 章节中深入介绍它们。

作业题

先自己做题目再看答案。

1. 两个函数 — 一个对象

重要程度:⭐️⭐️

是否可以创建像 new A()==new B() 这样的函数 AB

function A() { ... }function B() { ... }let a = new A;let b = new B;

alert( a == b ); // true复制代码
Copy after login

如果可以,请提供一个它们的代码示例。

2. 创建 new Calculator

重要程度:⭐️⭐️⭐️⭐️⭐️

创建一个构造函数 Calculator,它创建的对象中有三个方法:

  • read() 使用 prompt 请求两个值并把它们记录在对象的属性中。
  • sum() 返回这些属性的总和。
  • mul() 返回这些属性的乘积。

例如:

let calculator = new Calculator();
calculator.read();

alert( "Sum=" + calculator.sum() );
alert( "Mul=" + calculator.mul() );复制代码
Copy after login

3. 创建 new Accumulator

重要程度:⭐️⭐️⭐️⭐️⭐️

创建一个构造函数 Accumulator(startingValue)

它创建的对象应该:

  • 将“当前 value”存储在属性 value 中。起始值被设置到构造器 startingValue 的参数。
  • read() 方法应该使用 prompt 来读取一个新的数字,并将其添加到 value 中。

换句话说,value 属性是所有用户输入值与初始值 startingValue 的总和。

下面是示例代码:

let accumulator = new Accumulator(1); // 初始值 1accumulator.read(); // 添加用户输入的 valueaccumulator.read(); // 添加用户输入的 valuealert(accumulator.value); // 显示这些值的总和复制代码
Copy after login

相关免费学习推荐:JavaScript(视频)

The above is the detailed content of Detailed explanation of JavaScript constructor and 'new' operator. 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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
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 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

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.

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

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

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 and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

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

See all articles