Detailed explanation of several ways to write private variables of ES6 implementation class

Detailed explanation of several ways to write private variables of ES6 implementation class

Closure implementation of private variables

Private variables are not shared

Through the new keyword, the this inside the person constructor will point to Tom, opening up a new space and executing all the steps again.

class Person{ 
    constructor(name){ 
      let _num = 100; 

      this.name = name;
      this.getNum = function(){
        return _num;
      } 
      this.addNum = function(){
        return ++_num
      } 
    }
  }
  
  const tom = new Person('tom')
  const jack = new Person('jack')
  tom.addNum() 
  console.log(tom.getNum()) //101
  console.log(jack.getNum()) //100 

Private variables can be shared

To avoid generating a new private variable for each function, which would cause the problem that some variables cannot be shared, we can put this private variable outside the class constructor and continue to return this variable through a closure.

const Person = (function () {
    let _num = 100;

    return class _Person {
      constructor(name) {
        this.name = name; 
      }
      addNum() {
       return ++_num
      }
      getNum() {
       return _num
      } 
    }
  })() 

  const tom = new Person('tom')
  const jack = new Person('jack') 
  tom.addNum()
  console.log(tom.getNum()) //101
  console.log(jack.getNum()) //101

In this case, if the two methods are mixed, you can have two types of private variables, sharable and non-sharable.

Disadvantages: Many copies will be added during instantiation, which consumes more memory.

Symbol implements private variables of class

Symbol Introduction:

Create a unique value. All Symbols are not equal to each other. When creating a Symbol, you can add a description Symbol ("desc") to it. Currently, the key of the object also supports Symbol.

const name = Symbol('name')
const person = { // class name [name]: 'www',
  say(){
    console.log(`name is ${this[name]} `) 
  } 
} 
person.say()
console.log(name)

The key created by using Symbol for the object cannot be iterated and serialized by Json, so its main function is to add a unique value to the object.
But you can use getOwnProporitySymbols() to get the Symbol.
Disadvantages: The new syntax is not widely compatible with browsers.

Symbol private variables of the implementation class

It is recommended to use closures to create a reference to a Symbol, so that you can obtain this reference in the method area of ​​the class, avoiding the situation where all methods are written in the constructor and space is allocated to assign methods every time a new instance is created, resulting in memory waste.

const Person = (function () {
 let _num = Symbol('_num: private variable');
 
 return class _Person {
  constructor(name) {
   this.name = name;
   this[_num] = 100
  }
  addNum() {
   return ++this[_num]
  }
  getNum() {
   return this[_num]
  } 
 }
})()

const tom = new Person('tom')
const jack = new Person('jack')

console.log(tom.addNum()) //101 
console.log(jack.getNum()) //100

Creating private variables through weakmap

About MDN

accomplish:

const Parent = (function () {
 const privates = new WeakMap();

 return class Parent {
  constructor() {
   const me = {
    data: "Private data goes here"
   };
   privates.set(this, me);
  }
  getP() {
   const me = privates.get(this);
   return me
  }
 } 
})()

let p = new Parent()
console.log(p)
console.log(p.getP())

Summarize

In summary, the weakmap method can save memory, be easy to recycle, and be compatible with more browsers, which is also the most recommended implementation method.

This concludes this article on several ways to write private variables in ES6 implementation classes. For more information about private variables in ES6 classes, please search for 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:
  • Detailed explanation of the implementation of private variables in the ES6 series

<<:  Share 9 Linux Shell Scripting Tips for Practice and Interviews

>>:  A brief discussion on the manifestation and value selection method of innodb_autoinc_lock_mode

Recommend

HTML markup language - table tag

Click here to return to the 123WORDPRESS.COM HTML ...

In-depth analysis of MySQL database transactions and locks

Table of contents 1. Basic Concepts ACID 3.AutoCo...

Understanding Nginx Current Limitation in One Article (Simple Implementation)

Nginx is now one of the most popular load balance...

Example tutorial on using the sum function in MySQL

Introduction Today I will share the use of the su...

Tutorial on installing MySQL 5.6 using RPM in CentOS

All previous projects were deployed in the Window...

Storage engine and log description based on MySQL (comprehensive explanation)

1.1 Introduction to storage engines 1.1.1 File sy...

How to deploy nodejs service using Dockerfile

Initialize Dockerfile Assuming our project is nam...

Summary of basic knowledge and operations of MySQL database

This article uses examples to explain the basic k...

Solutions to the Problem of Creating XHTML and CSS Web Pages

The solutions to the problems encountered during x...

Detailed explanation of uniapp's global variable implementation

Preface This article summarizes some implementati...

React implements double slider cross sliding

This article shares the specific code for React t...

The use of textarea in html and common problems and case analysis

The textarea tag is an HTML tag that we often use....

Vue implements graphic verification code login

This article example shares the specific code of ...

Pure CSS drop-down menu

Achieve results Implementation Code html <div ...