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

How to encapsulate the carousel component in Vue3

Purpose Encapsulate the carousel component and us...

Multi-service image packaging operation of Dockerfile under supervisor

Writing a Dockerfile Configure yum source cd /tmp...

TypeScript learning notes: type narrowing

Table of contents Preface Type Inference Truth va...

Share MySql8.0.19 installation pit record

The previous article introduced the installation ...

How to use docker compose to build fastDFS file server

The previous article introduced a detailed exampl...

CentOS7 deployment Flask (Apache, mod_wsgi, Python36, venv)

1. Install Apache # yum install -y httpd httpd-de...

You may not know these things about Mysql auto-increment id

Introduction: When using MySQL to create a table,...

js realizes the image cutting function

This article example shares the specific code of ...

Detailed explanation of JavaScript implementation of hash table

Table of contents 1. Hash table principle 2. The ...

Discussion on Web Imitation and Plagiarism

A few months after entering the industry in 2005, ...

MySQL Learning: Three Paradigms for Beginners

Table of contents 1. Paradigm foundation 1.1 The ...

Detailed explanation of JDBC database link and related method encapsulation

Detailed explanation of JDBC database link and re...

SVG+CSS3 to achieve a dynamic wave effect

A vector wave <svg viewBox="0 0 560 20&qu...