简体   繁体   English

带有let的JS / ECMAScript6私有字段的模式?

[英]Pattern for JS/ECMAScript6 private fields with let?

I'm new to JS, so I'm trying to find a good pattern for having private fields with ECMAScript 6. 我是JS的新手,所以我正在尝试寻找一种使用ECMAScript 6具有私有字段的良好模式。

I'm using ES6's classes running on Node.js (latest version). 我正在使用在Node.js(最新版本)上运行的ES6类。 I came up with the following snippet but I don't understand why a variable declared with let (which in my probably-incorrect-understanding has only block scope in ES6) will survive after the block has been executed: 我想出了以下代码段,但我不明白为什么用let声明的变量(在我看来可能是不正确的理解中,它仅在ES6中具有块作用域)在执行完该块后仍然存在:

 class PrivateTest { constructor(aNumber) { let _aNumber = aNumber; //Privileged setter/getter with access to private _number: this.aNumber = function(value) { if (value !== undefined && (typeof value === typeof _aNumber)) { _aNumber = value; } else { return _aNumber; } } } } const privateTest = new PrivateTest(99); console.log(privateTest.aNumber()); privateTest.aNumber(86); console.log(privateTest.aNumber()); console.log(privateTest._aNumber); //Undefined. // Just to try inheritance: class PrivateTest2 extends PrivateTest { } const privateTest2 = new PrivateTest2(13); console.log(privateTest2.aNumber()); 

The output is this: 输出是这样的:

99
86
undefined
13

From the code above, it seems that this private field can even be inherited. 从上面的代码看来,这个私有字段甚至可以被继承。

So the questions are: 所以问题是:

  • Am I doing right? 我做对了吗?
  • What's the life cycle of _number supposed to be? _number的生命周期应该是多少?

Your _aNumber (declared with let _aNumber = aNumber ) doesn't exist outside of the class scope. 您的_aNumber (用let _aNumber = aNumber声明)在类范围之外不存在。 You would get undefined if you tried to do console.log(_aNumber) . 如果尝试执行console.log(_aNumber)则会得到undefined

But JavaScript has something called closures that "freeze" variables inside of functions. 但是JavaScript有一种叫做闭包的东西,可以“冻结”函数内部的变量。 This means that when you call the aNumber method of your class, the let variables still exist within that function. 这意味着,当您调用类的aNumber方法时, let变量仍存在于该函数中。

Also, because JavaScript functions are first-class, assigning this.aNumber to a value is exactly equivalent to assigning this.aNumber to a function that returns a value, and then calling that function. 另外,由于JavaScript函数是一类的,因此,将this.aNumber分配给一个值完全等同于将this.aNumber分配给一个返回值的函数,然后调用该函数。

Eg, 例如,

let a = 'foo';
let b = function() {
  return 'foo';
};

b();

console.log(a); // foo
console.log(b); // foo

It's tough to say if you are "doing it right", as I'm not exactly sure what you are going for. 很难说您是否“做对了”,因为我不确定您要干什么。 But learning more about closures and first-class functions might help you have a better grasp on the lifecycle of variables and the nature of variable assignments. 但是,了解有关闭包一流函数的更多信息可能会帮助您更好地掌握变量的生命周期和变量赋值的性质。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM