编程知识 cdmana.com

Explain JavaScript constructor and '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

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() {
  alert(new.target);
}

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

summary

  • 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();
calculator.read();

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 .

版权声明
本文为[LeviDing]所创,转载请带上原文链接,感谢

Scroll to Top