Two ways to declare private variables in JavaScript

Two ways to declare private variables in JavaScript

Preface

JavaScript is not like other languages ​​that can use keywords to declare private variables.
I know of two ways to declare private variables in JavaScript, one is to use closures, and the other is to use WeakMap.

Closures

There are many ways to describe closures, such as:
Functions that can access the scope of other functions;
A bridge for inner functions to access outer function scopes;
......

The logic of using closures to construct private variables is:
1. Declare variables and internal functions in external functions;
2. Use internal functions to access or modify variable values;
3. Return the inner function in the outer function;

function outside(){
	let val = 123;
	function inside(){
		return val;
	}
	return inside;
}
console.log(outside()());//123

The example above gives us a general idea of ​​the logic of using closures to build private variables, but it is not enough to reflect the importance of private variables. A const variable can also achieve the effect of the above code:

//The same can be accessed, but not modified, achieving the effect of the above code const val = 123;
console.log(val);//123

The following code will specifically reflect the importance of private variables:

function person(){ 
 let _name = 'unknown';
 let _age = 18;
 let _sex = 'man';

 function setName(name){
  _name = name || 'unknown';
 }

 function getName(){
  return _name;
 }

 function setAge(age){
  if(typeof age === 'number'){
   _age = Math.floor(age);
  }else{
   throw Error("typeof age !== 'number'");
  }
 }

 function getAge(){
  return _age;
 }

 function setSex(sex){
  if(sex === 'man' || sex === 1){
   _sex = 'man';
  }else if(sex === 'woman' || sex === 0){
   _sex = 'woman';
  }else{
   throw Error('input error');
  }
 }

 function getSex(){
  return _sex;
 }

 return {
  setName : setName,
  getName : getName,
  setAge : setAge,
  getAge : getAge,
  setSex : setSex,
  getSex : getSex
 }
}

let xiaoming = person();
let xiaohong = person();
xiaoming.setName('xiaoming');
xiaohong.setName('xiaohong');
console.log('xiaoming name : ' + xiaoming.getName());//xiaoming name : xiaoming
console.log('xiaohong name : ' + xiaohong.getName());//xiaohong name : xiaohong

xiaoming.setAge(19.3333);
xiaohong.setAge('16');//Uncaught Error: typeof age !== 'number'
console.log('xiaoming age : ' + xiaoming.getAge());//xiaoming age : 19
console.log('xiaohong age : ' + xiaohong.getAge());//xiaohong age : 18


xiaoming.setSex(1);
xiaohong.setSex('woman');
console.log('xiaoming sex : ' + xiaoming.getSex());//xiaoming sex : man
console.log('xiaohong sex : ' + xiaohong.getSex());//xiaohong sex : woman

From the above code, we can see that if we want to set or get the values ​​of the three variables _name, _age, and _sex, we can only use the fixed methods such as setName, getName, setAge, getAge, setSex, getSex, etc., and in all setter methods, the formal parameters are judged. This means that all operations on the object will be under control, which to some extent weakens some of the negative effects of JavaScript as a weakly typed language.

WeakMap

If you don’t know much about WeakMap, you can first read the detailed introduction of WeakMap.
The main point here is that the key of WeakMap is not enumerable.

let nameWeakMap = new WeakMap();
let ageWeakMap = new WeakMap();
let sexWeakMap = new WeakMap();

function person(){
 let _hash = Object.create(null);
 nameWeakMap.set(_hash,'unknown');
 ageWeakMap.set(_hash,18);
 sexWeakMap.set(_hash,'man');
 function setName(name){
  nameWeakMap.set(_hash,name || 'unknown');
 }

 function getName(){
  return nameWeakMap.get(_hash);
 }

 function setAge(age){
  if(typeof age === 'number'){
   ageWeakMap.set(_hash,Math.floor(age));
  }else{
   throw Error("typeof age !== 'number'");
  }
 }

 function getAge(){
  return ageWeakMap.get(_hash);
 }

 function setSex(sex){
  if(sex === 'man' || sex === 1){
   sexWeakMap.set(_hash,'man');
  }else if(sex === 'woman' || sex === 0){
   sexWeakMap.set(_hash,'woman');
  }else{
   throw Error('input error');
  }
 }

 function getSex(){
  return sexWeakMap.get(_hash);
 }

 return {
  setName : setName,
  getName : getName,
  setAge : setAge,
  getAge : getAge,
  setSex : setSex,
  getSex : getSex
 }
}

let xiaoming = person();
let xiaohong = person();
xiaoming.setName('xiaoming');
xiaohong.setName('xiaohong');
console.log('xiaoming name : ' + xiaoming.getName());//xiaoming name : xiaoming
console.log('xiaohong name : ' + xiaohong.getName());//xiaohong name : xiaohong

xiaoming.setAge(19.3333);
xiaohong.setAge('16');//Uncaught Error: typeof age !== 'number'
console.log('xiaoming age : ' + xiaoming.getAge());//xiaoming age : 19
console.log('xiaohong age : ' + xiaohong.getAge());//xiaohong age : 18


xiaoming.setSex(1);
xiaohong.setSex('woman');
console.log('xiaoming sex : ' + xiaoming.getSex());//xiaoming sex : man
console.log('xiaohong sex : ' + xiaohong.getSex());//xiaohong sex : woman

The same effect is achieved by building private variables. By the way, WeakMap is used to construct private variables in class.

Conclusion

This article only records what I know about the methods and functions of constructing private variables in JavaScript. If there are any errors or omissions, please point them out. Thank you very much.

The above are the details of the two ways to declare private variables in JavaScript. For more information about declaring private variables in JavaScript, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • JavaScript Advanced (I) Variable Declaration Improvement Example Analysis
  • Detailed explanation of the difference between let and var declaration variables in js
  • Detailed explanation of the difference between using and not using var in js variable declaration
  • Difference between JavaScript function declaration and variable declaration
  • A brief analysis of JavaScript variable declaration
  • Do you know variable declaration in JavaScript?

<<:  Linux automatically deletes logs and example commands from n days ago

>>:  HTTP and HTTP Collaboration Web Server Access Flow Diagram

Recommend

Two ways to manage volumes in Docker

In the previous article, I introduced the basic k...

Implementation of mysql8.0.11 data directory migration

The default storage directory of mysql is /var/li...

Zookeeper stand-alone environment and cluster environment construction

1. Single machine environment construction# 1.1 D...

Perfect solution to Docker Alpine image time zone problem

Recently, when I was using Docker to deploy a Jav...

Docker installation of MySQL (8 and 5.7)

This article will introduce how to use Docker to ...

JS implements random generation of verification code

This article example shares the specific code of ...

A small question about the execution order of SQL in MySQL

I encountered a sql problem at work today, about ...

Vue custom bullet box effect (confirmation box, prompt box)

This article example shares the specific code of ...

Analysis of MySQL example DTID master-slave principle

Table of contents 1. Basic Concepts of GTID 2. GT...

How to modify the contents of an existing Docker container

1. Docker ps lists containers 2. Docker cp copies...

Use Vue3 to implement a component that can be called with js

Table of contents Preface 1. Conventional Vue com...

MySQL data insertion efficiency comparison

When inserting data, I found that I had never con...

jQuery canvas generates a poster with a QR code

This article shares the specific code for using j...

VMware ESXI server virtualization cluster

Table of contents summary Environment and tool pr...