我们如何通过私有类字段进行枚举?
class Person {
#isFoo = true;
#isBar = false;
constructor(first, last) {
this.firstName = first;
this.lastName = last;
}
enumerateSelf() {
console.log(this);
// (pub/priv fields shown)
// enumerate through instance fields
for (let key in this) {
console.log(key)
// (only public fields shown)
}
// How do we enumerate/loop through private fields too?
}
}
new Person('J', 'Doe').enumerateSelf();
It's 不可能。他们是私人领域,并且没有枚举方法。只有类声明静态地知道声明了哪些类。它们不是属性,甚至没有代表私有名称的语言值,您无法动态访问它们 (就像括号符号一样).
你会得到的最好的就是
enumerateSelf() {
console.log(this);
for (let key in this) {
console.log("public", key, this[key]);
}
console.log("private isFoo", this.#isFoo);
console.log("private isBar", this.#isBar);
}
有一个悬而未决的问题在关于“的私人领域提案”中私有字段迭代”,然而 TC39 成员国的第一个评论是“私有字段不是属性。你无法通过设计来反思它们。".
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)