gpt4 book ai didi

javascript - 如何枚举私有(private) JavaScript 类字段

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:56:17 24 4
gpt4 key购买 nike

我们如何通过私有(private)类字段进行枚举?

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();

最佳答案

不可能。它们是私有(private)字段,并且没有针对它们的枚举方法。只有类声明静态地知道声明了哪些。它们不是属性,甚至没有表示私有(private)名称的语言值,你 cannot access them dynamically (like with bracket notation)。

你会得到最好的是

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);
}

an open issue在关于“私有(private)字段迭代”的私有(private)字段提案中,然而 TC39 成员的第一批评论之一是“私有(private)字段不是属性。你不能通过设计来反射(reflect)它们.”。

关于javascript - 如何枚举私有(private) JavaScript 类字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58475427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com