JavaScript Two Ways to Declare Private Variables

  • 2021-10-25 06:02:30
  • OfStack

Preface

Unlike other languages, JavaScript can use keywords to declare private variables.
I know that JavaScript can be used to declare private variables in two ways, one is using closures, and the other is using WeakMap.

Closure

There are many descriptions of closures, such as:
Functions that can access the scope of other functions;
A bridge for internal functions to access the scope of external functions;
......

The logic for building private variables using closures 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 within the outer function;


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

Through my above example, we can roughly understand the logic of building private variables using closures, but it is not enough to reflect the importance of private variables. One const variable can also achieve the effect of the above code:


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

The following code will embody 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, it can be seen that if you want to set or get the values of _ name, _ age and _ sex, you can only use fixed methods such as setName, getName, setAge, getAge, setSex and getSex, and in all setter methods, the formal parameters are judged. This means that all operations on the object will be under control, which weakens some of the negative effects of JavaScript as a weakly typed language at a certain level.

WeakMap

If you don't know much about WeakMap, you can see the detailed introduction of WeakMap first.
Here, we mainly use key of WeakMap to enumerate this knowledge point.


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 effect of building private variables is also achieved. By the way, WeakMap is used to build private variables in class.

End

This article only records what I know about how JavaScript builds private variables and how it works. If there are any mistakes or omissions, please point them out. Thank you very much.

These are the details of JavaScript's two ways to declare private variables. For more information about JavaScript's declaration of private variables, please pay attention to other related articles on this site!


Related articles: