如何在不使用弱图的情况下将私人数据添加到arbitary对象
好的。这不是一个问题,而是我今天有一个顿悟 我想分享,因为我不知道是否有人意识到。
考虑以下代码:
function Id(obj) {
return obj;
}
class Meta extends Id {
#data;
constructor(obj, data) {
super(obj);
this.#data = data;
}
getData() {
try {
return this.#data;
} catch (ex) {}
}
setData(value) {
try {
this.#data = value;
} catch (ex) {
new Meta(this, value);
}
}
static get = Function.call.bind(this.prototype.getData);
static set = Function.call.bind(this.prototype.setData);
}
var obj = Object.freeze({}); // !!!! frozen
console.log(Meta.get(obj)); // undefined
Meta.set(obj, "test");
console.log(Meta.get(obj)); // "test"
console.log(Reflect.ownKeys(obj)); // Array []
如您所见,我在外部冷冻对象中添加了一个私有变量,该变量只能通过我的代码访问。
感谢您阅读和享受!
Ok. This isn't really a question but rather an epiphany I had today
that I would like to share, because I don't know if anyone realizes it.
Consider the following code:
function Id(obj) {
return obj;
}
class Meta extends Id {
#data;
constructor(obj, data) {
super(obj);
this.#data = data;
}
getData() {
try {
return this.#data;
} catch (ex) {}
}
setData(value) {
try {
this.#data = value;
} catch (ex) {
new Meta(this, value);
}
}
static get = Function.call.bind(this.prototype.getData);
static set = Function.call.bind(this.prototype.setData);
}
var obj = Object.freeze({}); // !!!! frozen
console.log(Meta.get(obj)); // undefined
Meta.set(obj, "test");
console.log(Meta.get(obj)); // "test"
console.log(Reflect.ownKeys(obj)); // Array []
As you can see, I added a private variable to an external frozen object that can be accessed only by my code.
Thank you for reading and enjoy!!!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论