东丽做网站公司,网站建设推广公司价格,一个网站只有一个核心关键词,wordpress双数据库要扩展loganfsmyth的回答#xff1a;JavaScript中唯一真正私有的数据仍然是作用域变量。不能以与公共属性相同的方式在内部访问私有属性#xff0c;但是可以使用范围变量来存储私有数据。作用域变量这里的方法是使用构造函数的作用域(它是私有的)来存储私有数据。要使方法能够…要扩展loganfsmyth的回答JavaScript中唯一真正私有的数据仍然是作用域变量。不能以与公共属性相同的方式在内部访问私有属性但是可以使用范围变量来存储私有数据。作用域变量这里的方法是使用构造函数的作用域(它是私有的)来存储私有数据。要使方法能够访问这些私有数据它们也必须在构造函数中创建这意味着您要用每个实例重新创建它们。这是一个性能和内存的惩罚但一些人认为这个惩罚是可以接受的。可以避免对不需要访问私有数据的方法进行惩罚方法可以像往常一样将它们添加到原型中。例子function Person(name) {let age 20; // this is privatethis.name name; // this is publicthis.greet function () {// here we can access both name and ageconsole.log(name: ${this.name}, age: ${age});};}let joe new Person(Joe);joe.greet();// here we can access name but not age作用域WeakMapWeakMap可以用来避免先前方法的性能和内存损失。WeakMaps将数据与对象(此处为实例)关联起来使其只能使用该WeakMap进行访问。因此我们使用作用域变量方法创建私有WeakMap然后使用该WeakMap检索与this..这比作用域变量方法更快因为所有实例都可以共享一个WeakMap因此您不需要仅仅为了使它们访问自己的WeakMaps而重新创建方法。例子let Person (function () {let privateProps new WeakMap();class Person {constructor(name) {this.name name; // this is publicprivateProps.set(this, {age: 20}); // this is private}greet() {// Here we can access both name and ageconsole.log(name: ${this.name}, age: ${privateProps.get(this).age});}}return Person;})();let joe new Person(Joe);joe.greet();// here we can access joes name but not age本例使用一个对象对多个私有属性使用一个WeakMap您还可以使用多个WeakMaps并使用它们如下age.set(this, 20)或者编写一个小包装并以另一种方式使用它如privateProps.set(this, age, 0).从理论上讲这种方法的隐私可能会被篡改全球的行为所破坏。WeakMap对象。也就是说所有的JavaScript都可能被破损的全局破坏。我们的代码已经建立在这样的假设之上。(这个方法也可以用Map但是WeakMap更好是因为Map除非您非常小心否则将产生内存泄漏为此目的两者在其他方面并没有什么不同。)半答案限定范围的符号符号是一种可以用作属性名称的原语值类型。可以使用作用域变量方法创建私有符号然后将私有数据存储在this[mySymbol].此方法的隐私可能会被侵犯Object.getOwnPropertySymbols但做起来有点尴尬。例子let Person (function () {let ageKey Symbol();class Person {constructor(name) {this.name name; // this is publicthis[ageKey] 20; // this is intended to be private}greet() {// Here we can access both name and ageconsole.log(name: ${this.name}, age: ${this[ageKey]});}}return Person;})();let joe new Person(Joe);joe.greet();// Here we can access joes name and, with a little effort, age. ageKey is// not in scope, but we can obtain it by listing all Symbol properties on// joe with Object.getOwnPropertySymbols(joe).半答案下划线旧的默认值只需使用带有下划线前缀的公共属性。尽管在任何情况下都不是私有财产但这种约定非常普遍因此它很好地传达了读者应该将该财产视为私有财产这通常会使工作完成。作为交换我们得到了一种更容易阅读、更容易打字和更快的方法。例子class Person {constructor(name) {this.name name; // this is publicthis._age 20; // this is intended to be private}greet() {// Here we can access both name and ageconsole.log(name: ${this.name}, age: ${this._age});}}let joe new Person(Joe);joe.greet();// Here we can access both joes name and age. But we know we arent// supposed to access his age, which just might stop us.结语截至2017年私人地产仍没有完美的做法。各种方法各有优缺点。作用域变量是真正的私有变量作用域WeakMaps非常私有比作用域变量更实用作用域符号具有合理的私有性和合理的实用性下划线通常具有足够的私有性和非常实用性。