Private property in js class
class Person {
constructor(name) {
this.name = name // Public attributes}}Copy the code
class
The keyword is just syntax sugar, no can be implemented
class Login {
constructor(username, password) {
this.username = username
this.password = password
}
}
const xguo = new Login('guo'.'88888888')
Copy the code
-
How do I make the password property private? That is, out of class is not accessible
-
Closure?
let obj = (function() {
// Closed Spaces are private
return () = >{}}) ()Copy the code
-
Closure, where local variables can be read only by children inside a function
-
How do I set up a key stored in an object that is not externally accessible? Symbol!
class Login {
constructor(username, password) {
this.username = username
const PASSWORD = Symbol(a)this[PASSWORD] = password
}
checkPassword(pwd) {
return this[PASSWORD] == pwd
}
}
var userA = new Login('aa'.'123456')
console.log(userA.checkPassword(123456));
Copy the code
-
Symbol sets a unique key to avoid public access
-
How do you access the symbol as key property in the object?
const gender = Symbol('gender')
const obj = {
name: 'guo'.age: 17,
[gender]: 'man'
}
console.log(obj[gender]); // man
console.log(Object.getOwnPropertySymbols(obj)); // [ Symbol(gender) ]
console.log(Reflect.ownKeys(obj)); // [ 'name', 'age', Symbol(gender) ]
Copy the code
- You can use
Object.getOwnPropertySymbols()
andReflect.ownKeys()
Get to the