search
HomeWeb Front-endJS TutorialDetailed explanation of JavaScript constructor and 'new' operator

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复制代码

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;(隐式返回)}复制代码

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

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

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;  // ……用于用户创建的其他代码
  // 也许是复杂的逻辑和语句
  // 局部变量等};复制代码

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 { ... }复制代码

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复制代码

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" };  // <p>Here is an example where <code>return</code> is empty (Or we could put a primitive type after it, no effect): </p><pre class="brush:php;toolbar:false">function SmallUser() {  this.name = "John";  return; // <p>Normally constructors don't have a <code>return</code> statement. Here we mention the special behavior of returned objects mainly for completeness. </p><h3 id="Omit-brackets">Omit brackets</h3><p>By the way, if there are no parameters, we can omit the brackets after <code>new</code>: </p><pre class="brush:php;toolbar:false">let user = new User; // <p>Omitting brackets here is not considered A "good style", but the syntax is allowed by the specification. </p><h2 id="Methods-in-constructors">Methods in constructors</h2><p>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. </p><p>当然,我们不仅可以将属性添加到 <code>this</code> 中,还可以添加方法。</p><p>例如,下面的 <code>new User(name)</code> 用给定的 <code>name</code> 和方法 <code>sayHi</code> 创建了一个对象:</p><pre class="brush:php;toolbar:false">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() { ... }
}
*/复制代码

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

总结

  • 构造函数,或简称构造器,就是常规函数,但大家对于构造器有个共同的约定,就是其命名首字母要大写。
  • 构造函数只能使用 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复制代码

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

2. 创建 new Calculator

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

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

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

例如:

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

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

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); // 显示这些值的总和复制代码

相关免费学习推荐: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
This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
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 Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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.