Detailed description of the function of new in JS

Detailed description of the function of new in JS

Introduction:

Most articles about new will start with object-oriented thinking, but I always believe that when explaining one thing, another more complex thing should not be introduced.

Imagine we are making a strategy war game where players can control a bunch of soldiers to attack the enemy.

Let’s focus on the “making soldiers” part of this game.

A soldier is represented by a bunch of attributes in the computer, as shown below:

1. Example

We can create a soldier just like this:

var Soldier = {
  ID: 1, // Used to distinguish each soldier's type: "American Soldier",
  Attack power: 5,
  HP:42, 
  Walking: function(){ /*code for walking two steps*/},
  Run: function(){ /*Running code*/ },
  Death: function(){ /*Go die*/ },
  Attack: function(){ /*Brush his bear face*/ },
  Defense: function(){ /*Protect the face*/ }
}

Barracks. Manufacturing (soldiers)

2. Create 100 soldiers

What if you need to create 100 soldiers?

Let’s loop 100 times:

var soldiers = []
var Soldier for(var i=0; i<100; i++){
  Soldier = {
    ID: i, // ID cannot be repeated. Soldier: "American Soldier",
    Attack power: 5,
    HP:42, 
    Walking: function(){ /*code for walking two steps*/},
    Run: function(){ /*Running code*/ },
    Death: function(){ /*Go die*/ },
    Attack: function(){ /*Brush his bear face*/ },
    Defense: function(){ /*Protect the face*/ }
  }
  Soldiers.push(soldier)
}

Barracks. Mass production (soldiers)

3. Questioning

There is a problem with the code above: a lot of memory is wasted.

  • The five actions of walking, running, dying, attacking, and defending are actually the same for each soldier. You only need to reference the same function. There is no need to repeatedly create 100 walking, 100 running, etc.
  • These soldiers have the same type and attack power, so there is no need to create them 100 times.
  • Only the ID and health values ​​need to be created 100 times, because each soldier has his own ID and health values.

4. Improvements

Those who have read our previous column articles (JS prototype chain) must know that the prototype chain can solve the problem of repeated creation: we first create a "soldier prototype", and then let __proto__ of "soldier" point to the "soldier prototype"

var SoldierPrototype = {
  Arms: "American Soldier",
  Attack power: 5,
  Walking: function(){ /*code for walking two steps*/},
  Run: function(){ /*Running code*/ },
  Death: function(){ /*Go die*/ },
  Attack: function(){ /*Brush his bear face*/ },
  Defense: function(){ /*Protect the face*/ }
}
var soldiers = []
var Soldier for(var i=0; i<100; i++){
  Soldier = {
    ID: i, // ID cannot be repeated Life value: 42
  }

  /*Don't write this in actual work, because __proto__ is not a standard attribute*/
  Soldier.__proto__ = Soldier prototype Soldiers.push(Soldier)
}

Barracks. Mass production (soldiers)

5. Elegant?

Someone pointed out that it's not elegant to have the code for creating a soldier in two places, so we use a function to connect the two parts:

function soldier(ID){
  var temporary object = {}

  temporary object.__proto__ = soldier.prototype temporary object.ID = ID
  TemporaryObject.LifeValue = 42
  
  return temporary object}

Soldier.Prototype = {
  Arms: "American Soldier",
  Attack power: 5,
  Walking: function(){ /*code for walking two steps*/},
  Run: function(){ /*Running code*/ },
  Death: function(){ /*Go die*/ },
  Attack: function(){ /*Brush his bear face*/ },
  Defense: function(){ /*Protect the face*/ }
}

// Save as file: soldier.js

Then you can happily reference "Soldier" to create a soldier:

var soldiers = []
for(var i=0; i<100; i++){
  soldiers.push(soldier(i))
}

Barracks. Mass production (soldiers)

6. Care from the Father of JS

The creator of JS created the new keyword, which allows us to write fewer lines of code:

As long as you use the new keyword before the soldier, you can do four less things:

  • No need to create temporary objects, because new will do it for you (you can access the temporary object using " this ");
  • No need to bind a prototype, because new will do it for you ( new specifies the prototype name as prototype in order to know where the prototype is);
  • No need return a temporary object, because new will do it for you;
  • Don't think of a name for the prototype, because new specifies the name prototype .

7. This time we use new to write

function soldier(ID){
  this.ID = ID
  this.health = 42
}

Soldier.prototype = {
  Arms: "American Soldier",
  Attack power: 5,
  Walking: function(){ /*code for walking two steps*/},
  Run: function(){ /*Running code*/ },
  Death: function(){ /*Go die*/ },
  Attack: function(){ /*Brush his bear face*/ },
  Defense: function(){ /*Protect the face*/ }
}

// Save as file: soldier.js

Then create the soldier (add a new keyword):

var soldiers = []
for(var i=0; i<100; i++){
  Soldiers.push(new Soldier(i))
}

Barracks. Mass production (soldiers)

The purpose of new is to save a few lines of code. (Also known as syntactic sugar)

8. Pay attention to the constructor attribute

In order to record "which function created the temporary object", the new operation adds a constructor attribute to " prototype " in advance:

Soldier.prototype = {
  constructor: Soldier}


If you reassign " prototype ", the constructor property will be gone, so you should write:

Soldier.prototype.ArmyType = "American Soldier"
Soldier.prototype.attack = 5
Soldier.prototype.walk = function(){ /*code for walking two steps*/}
Soldier.prototype.run = function(){ /*Running code*/ }
soldier.prototype.death = function(){ /*Go die*/ }
Soldier.prototype.attack = function(){ /*Brush his bear face*/ }
Soldier.prototype.defense = function(){ /*protect face*/ }


Or you can reassign constructor yourself:

Soldier.prototype = {
  constructor: Soldier,
  Arms: "American Soldier",
  Attack power: 5,
  Walking: function(){ /*code for walking two steps*/},
  Run: function(){ /*Running code*/ },
  Death: function(){ /*Go die*/ },
  Attack: function(){ /*Brush his bear face*/ },
  Defense: function(){ /*Protect the face*/ }
}

This is the end of this detailed article about the role of new in JS. For more information about the role of new in JS, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • The relationship between JS constructor and instantiation and prototype introduction
  • Detailed explanation of JavaScript prototype and examples
  • An article to help you understand Js inheritance and prototype chain
  • Summary and practice of javascript prototype chain diagram
  • Handwriting implementation of new in JS
  • How much do you know about JavaScript's constructor, prototype, prototype chain and new?

<<:  Docker image creation Dockerfile and commit operations

>>:  MySQL character types are case sensitive

Recommend

Detailed explanation of how to use the vue3 Teleport instant movement function

The use of vue3 Teleport instant movement functio...

Web data storage: Cookie, UserData, SessionStorage, WebSqlDatabase

Cookie It is a standard way to save the state of ...

40 CSS/JS style and functional technical processing

1- Styling dropdown select boxes - Modify the dro...

How to use limit_req_zone in Nginx to limit the access to the same IP

Nginx can use the limit_req_zone directive of the...

Usage of if judgment in HTML

In the process of Django web development, when wr...

Play with the connect function with timeout in Linux

In the previous article, we played with timeouts ...

A brief introduction to MySQL functions

Table of contents 1. Mathematical functions 2. St...

MySQL full-text search Chinese solution and example code

MySQL full text search Chinese solution Recently,...

Summary of learning Docker commands in one article

Table of contents Introduction Mirror repository ...

A practical record of checking and processing duplicate MySQL records on site

Table of contents Preface analyze Data Total Repe...

How to use Greek letters in HTML pages

Greek letters are a very commonly used series of ...

Implementation of docker redis5.0 cluster cluster construction

System environment: Ubuntu 16.04LTS This article ...

Sample code for batch deployment of Nginx with Ansible

1.1 Copy the nginx installation package and insta...