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

How to implement scheduled backup of MySQL database

1. Create a shell script vim backupdb.sh Create t...

Super detailed MySQL usage specification sharing

Recently, there have been many database-related o...

Introduction to Javascript DOM, nodes and element acquisition

Table of contents DOM node Element node: Text nod...

How to install theano and keras on ubuntu system

Note: The system is Ubuntu 14.04LTS, a 32-bit ope...

Implementation of MySQL Multi-version Concurrency Control MVCC

Table of contents What is MVCC MVCC Implementatio...

Understanding MySQL index pushdown in five minutes

Table of contents What is index pushdown? The pri...

Vue installation and use

Table of contents 1. Vue installation Method 1: C...

Vue custom table column implementation process record

Table of contents Preface Rendering setTable comp...

Implementation of multi-environment configuration (.env) of vue project

Table of contents What is multi-environment confi...

Using Openlayer in Vue to realize loading animation effect

Note: You cannot use scoped animations! ! ! ! via...

A QQ chat room based on vue.js

Table of contents Introduction The following is a...

How does Vue implement communication between components?

Table of contents 1. Communication between father...

Develop a vue component that encapsulates iframe

Table of contents 1. Component Introduction 2. Co...

Monitor the size change of a DOM element through iframe

A common problem encountered during the developme...