Get the App
SLTechnology News&Howtos  ›  Development  › 

How to implement Private variables in JavaScript

Shulou Source: shulou.com Published: 2022-06-01 05:31:12 10月03日 Update

This article mainly introduces JavaScript how to achieve private variables, the article is very detailed, has a certain reference value, interested friends must read it!

Implementation of private variables

Use the Proxy proxy to make all variables that start with _ inaccessible to the outside world

Save private variables in the form of closures. The disadvantage is that all instances of the class access the same private variables.

Another implementation of closures solves the shortcomings of the closures above. Each instance has its own private variable. The disadvantage is that it abandons the conciseness of class syntax and stores all privileged methods (methods that access private variables) in the constructor.

With WeakMap and closures, objects composed of the current instance and all private variables are saved at each instantiation. The WeakMap in the closure cannot be accessed externally. The advantage of using WeakMap is that there is no need to worry about memory overflow.

These are all the contents of the article "how JavaScript implements private variables". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Variables private closures instances shortcomings contents methods articles brevity value interests memory functions benefits objects guys buddies beginnings forms more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Linux MySQL Shulou Tech Info Huawei