How to define private variables in JavaScript

How to define private variables in JavaScript

Preface

Unlike other languages, JavaScript can use keywords to declare private variables.
I understand that JavaScript can be used to declare private variables in two ways, one is to useClosure, One is to useWeakMap

Closure

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

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 internal functions in external functions;

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

Through my above example, I can roughly understand the logic of using closures to construct 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:

//同样的能访问,但是不能修改,达到了上述代码的效果
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, it can be seen that if you want to set or get the values ​​of the three variables _name , _age , _sex , you can only use the fixed setName , getName , setAge , getAge , setSex , getSex and other methods. In the setter method, the formal parameters are judged. This means that all operations on the object will be under control, which at a certain level weakens some of the negative effects of JavaScript as a weakly typed language.

WeakMap

If you don’t know much about WeakMap, you can read the detailed introduction of WeakMap first .
This is mainly to use the knowledge 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 effect of constructing private variables is also achieved. By the way, WeakMap is used to construct private variables in class.

end

This article is just to record what I know about the method and function of JavaScript to build private variables. If there are errors or omissions, please point them out, thank you very much.

Guess you like

Origin blog.csdn.net/qq_35508835/article/details/108431649