Explain JavaScript constructor and 'new' operator

LeviDing 2020-11-12 22:02:05
explain javascript constructor new operator

Constructors and operators "new"

The conventional {...} Syntax allows you to create an object . But we often need to create many similar objects , For example, multiple users or menu items .

You can use constructors and "new" Operator to implement .


Constructors are technically conventional functions . But there are two agreements :

  1. They start with a capital letter .
  2. They can only be "new" Operator to execute .

for example :

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

When a function is used new When the operator executes , It follows these steps :

  1. A new empty object is created and assigned to this.
  2. Function body execution . Usually it changes this, Add new properties to it .
  3. return this Value .

let me put it another way ,new User(...) It's something like that :

function User(name) {
// this = {};( Implicitly create )
// Add attributes to this
this.name = name;
this.isAdmin = false;
// return this;( Implicit return )

therefore new User("Jack") The result is 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. . It's much shorter than using literal values every time , And it's easier to read .

This is the main purpose of the constructor —— Implement reusable object creation code .

Let's emphasize again —— Technically speaking , Any function can be used as a constructor . namely : Any function can go through new To run the , It will execute the algorithm above .“ title case ” It's a common agreement , To explicitly indicate that a function will be used new To run the .

new function() { ... }

If we have many lines of code for creating a single complex object , We can encapsulate them in constructors , like this :

let user = new function() {
this.name = "John";
this.isAdmin = false;
// …… For other user created code
// Maybe it's complicated logic and statements
// Local variables, etc

Constructor cannot be called again , Because it's not stored anywhere , It's just created and called . therefore , The trick is to encapsulate the code that builds a single object , Without having to reuse it in the future .

Constructor pattern testing :new.target

Advanced content :

The grammatical content in this section is rarely used , Unless you want to know everything , Otherwise, you can skip the grammar directly .

Inside a function , We can use new.target Property to check if it is used new Called .

For regular calls , It is empty , For the use of new Call to , Is equal to the function :

function User() {
// No "new":
User(); // undefined
// belt "new":
new User(); // function User { ... }

It can be used inside functions , To determine whether the function is passed by new Called “ Constructor mode ”, Still not passed new Called “ Normal mode ”.

We can also let new Calls do the same thing as regular calls , like this :

function User(name) {
if (!new.target) { // If you don't pass new Run me
return new User(name); // …… I will add new
this.name = name;
let john = User("John"); // Redirect the call to the new user
alert(john.name); // John

This method is sometimes used in libraries to make syntax more flexible . So when people call functions , Whether or not you use new, All programs work .

however , It's not a good thing to use it everywhere , Because it's omitted new Makes it hard to see what's going on in the code . And by new We all know that this creates a new object .

Constructor's return

Usually , The constructor does not return sentence . Their job is to write everything necessary into this, And automatically converted to the result .

however , If there's one here return sentence , Then the rules are simple :

  • If return It returns an object , This object is returned , instead of this.
  • If return It's a primitive type , It ignores .

let me put it another way , With objects return Return the object , Return in all other cases this.

for example , here return An object is returned through an overlay this

function BigUser() {
this.name = "John";
return { name: "Godzilla" }; // <-- Return this object
alert( new BigUser().name ); // Godzilla, Got the object 

Here's one return Empty examples ( Or we can put a primitive type after it , No impact ):

function SmallUser() {
this.name = "John";
return; // <-- return this
alert( new SmallUser().name ); // John

Usually constructors don't have return sentence . Here we mainly talk about the special behavior of returning objects for the sake of integrity .

Omit parenthesis

By the way , If there are no parameters , We can omit new The brackets after :

let user = new User; // <-- No parameters
// Equate to
let user = new User();

Omitting brackets here is not considered a form of “ Good style ”, But the specification allows the syntax to be used .

Methods in constructors

Using constructors to create objects brings a lot of flexibility . Constructors may have some parameters , These parameters define how to construct the object and what to put in .

Of course , We can not only add attributes to this in , You can also add methods .

for example , Below new User(name) Use the given name And methods sayHi Created an object :

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() { ... }

class Is a more advanced syntax for creating complex objects , We'll talk about .


  • Constructors , Or constructor for short , It's a regular function , But there's a common agreement about constructors , The first letter of the name should be capitalized .
  • Constructors can only use new To call . Such a call means that an empty this, And at the end, it returns... Filled with values this.

We can use constructors to create multiple similar objects .

JavaScript Constructors are provided for many built-in objects : Such as date Date、 aggregate Set And other things we plan to learn .

object , We'll be back !

In this chapter , We only introduced the basics of objects and constructors . They are for us in the next chapter , It's important to learn more about data types and functions .

After we learned that , We're going back to the object , stay <info:prototypes> and <info:classes> They are introduced in detail in the chapter .

Homework questions

Do your own questions first and then look at the answers .

1. Two functions — An object

How important :️️

Can you create something like new A()==new B() A function like this A and B

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

If possible , Please provide a code example of them .

2. establish new Calculator

How important :️️️️️

Create a constructor Calculator, There are three methods in the object it creates :

  • read() Use prompt Request two values and record them in the object's properties .
  • sum() Returns the sum of these properties .
  • mul() Returns the product of these properties .

for example :

let calculator = new Calculator();
alert( "Sum=" + calculator.sum() );
alert( "Mul=" + calculator.mul() );

3. establish new Accumulator

How important :️️️️️

Create a constructor Accumulator(startingValue).

The object it creates should be :

  • take “ At present value” Stored in properties value in . The starting value is set to the constructor startingValue Parameters of .
  • read() The method should use prompt To read a new number , And add it to value in .

let me put it another way ,value Attributes are all user input values and initial values startingValue The sum of .

Here is the sample code :

let accumulator = new Accumulator(1); // Initial value 1
accumulator.read(); // Add user entered value
accumulator.read(); // Add user entered value
alert(accumulator.value); // Show the sum of these values 

answer :

The official account of WeChat 「 Technology talk 」 The background to reply 1-4-5 Get the answer to the assignment .

modern JavaScript course : Open source modern JavaScript From introduction to advanced quality course . React Official documents recommend , And MDN Side by side JavaScript Study the tutorial .

Read for free online :https://zh.javascript.info

Scan the qr code below , Pay attention to WeChat public number 「 Technology talk 」, Subscribe to more .


  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple