Implementation summary of private variables in ES6 (code example)
This article brings you a summary of the implementation of private variables in ES6 (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
When I read "Introduction to ECMAScript 6", I saw scattered implementations of private variables, so I will summarize it here.
1. Agreement
Implementation
class Example { constructor() { this._private = 'private'; } getName() { return this._private } } var ex = new Example(); console.log(ex.getName()); // private console.log(ex._private); // private
Advantages
Simple writing method
Easy debugging
Good compatibility
Disadvantages
-
External access and modification
The language does not have a matching mechanism. For example, the for in statement will enumerate all attributes
Naming conflict
2. Closure
Implementation of one
/** * 实现一 */ class Example { constructor() { var _private = ''; _private = 'private'; this.getName = function() {return _private} } } var ex = new Example(); console.log(ex.getName()); // private console.log(ex._private); // undefined
Advantages
No naming conflicts
- ##External Unable to access and modify
- The logic of the constructor becomes complicated. The constructor should only do object initialization. Now in order to implement private variables, it must include the implementation of some methods, and the code organization is slightly unclear.
- Methods exist on instances, not prototypes, and subclasses cannot use super to call
- Construction adds a little overhead
/**
* 实现二
*/
const Example = (function() {
var _private = '';
class Example {
constructor() {
_private = 'private';
}
getName() {
return _private;
}
}
return Example;
})();
var ex = new Example();
console.log(ex.getName()); // private
console.log(ex._private); // undefined
Advantages
- No naming conflict
- Cannot be accessed and modified externally
- The writing method is a bit complicated
- The construction adds a little overhead
const Example = (function() {
var _private = Symbol('private');
class Example {
constructor() {
this[_private] = 'private';
}
getName() {
return this[_private];
}
}
return Example;
})();
var ex = new Example();
console.log(ex.getName()); // private
console.log(ex.name); // undefined
Advantages
- No naming conflict
- Cannot be accessed and modified externally
- No performance loss
- Slightly written Complex
- The compatibility is also good
/**
* 实现一
*/
const _private = new WeakMap();
class Example {
constructor() {
_private.set(this, 'private');
}
getName() {
return _private.get(this);
}
}
var ex = new Example();
console.log(ex.getName()); // private
console.log(ex.name); // undefined
if written like this , you may feel that the encapsulation is not enough, you can also write like this:
/** * 实现二 */ const Example = (function() { var _private = new WeakMap(); // 私有成员存储容器 class Example { constructor() { _private.set(this, 'private'); } getName() { return _private.get(this); } } return Example; })(); var ex = new Example(); console.log(ex.getName()); // private console.log(ex.name); // undefinedAdvantages
- No naming conflicts
- External Unable to access and modify
- Writing is more troublesome
- Compatibility is a bit problematic
- There is a certain performance cost
class Point {
#x;
#y;
constructor(x, y) {
this.#x = x;
this.#y = y;
}
equals(point) {
return this.#x === point.#x && this.#y === point.#y;
}
}
So why not use private fields directly? For example:
class Foo { private value; equals(foo) { return this.value === foo.value; } }To put it simply, it is too troublesome, and of course there are performance considerations...For example, if we do not use #, but use the private keyword :
class Foo { private value = '1'; equals(foo) { return this.value === foo.value; } } var foo1 = new Foo(); var foo2 = new Foo(); console.log(foo1.equals(foo2));Here we create two new instances, and then pass foo2 as a parameter into the instance method of foo1. So can we get the value of foo2.value? If we directly
foo2.value we will definitely not be able to get the value. After all, it is a private variable, but equals is a class method of Foo, so can we get it?
Member functions of a class can access private variables of instances of the same type. This is because privateness is for implementation "External" information is hidden within the class itself. There is no need to prohibit access to private variables. You can also understand that the restrictions on private variables are based on the class, not the object. In addition, this can also provide users with Bring convenience.
Since it is possible to get the value, the printed result should be true, but what if the value we pass in is not an instance of Foo, but another object?var foo1 = new Foo(); console.log(foo1.equals({ value: 2 }));Of course the code here can run normally, but for the compiler, it is a little troublesome, because the compiler does not know whether value is a normal property or a private property of foo, so the compiler needs to do Judgment, first determine whether foo is an instance of Foo, and then obtain the value. This also means that such a judgment needs to be made for every attribute access, and the engine has been highly optimized around attribute access and is too lazy to change, and it also reduces the speed. But in addition to this work, there are some other things that need to be considered, such as:
- You must encode the private key into each lexical environment
- for in Can it be traversed through these properties?
- When private attributes and normal attributes have the same name, who will block whom?
- How to prevent the name of private attributes from being detected.
private slots method and use a new slot search syntax. In short, it will be better than The implementation of private is much simpler.
The above is the detailed content of Implementation summary of private variables in ES6 (code example). For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools
