Private properties
In ES6 (and before), all private property implementations rely on closure.
People have been doing it even before JavaScript has versions.
WeakMap is just a variation that removes the need of new scope and new functions for each new object, at cost of access speed.
Symbol is a ES6 variation that hides the attribute from common operations, such as simple property access or for in
.
var MyClass;
( () => {
// Define a scoped symbol for private property A.
const PropA = Symbol( 'A' );
// Define the class once we have all symbols
MyClass = class {
someFunction () {
return "I can read " + this[ PropA ]; // Access private property
}
}
MyClass.prototype[ PropA ] = 'Private property or method';
})();
// function in the closure can access the private property.
var myObject = new MyClass();
alert( myObject.someFunction() );
// But we cannot "recreate" the Symbol externally.
alert( myObject[ Symbol( 'A' ) ] ); // undefined
// However if someone *really* must access it...
var symbols = Object.getOwnPropertySymbols( myObject.__proto__ );
alert( myObject[ symbols[ 0 ] ] );
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…