我正在研究代理对象、类和私有属性。
并遇到了这个错误消息:
/home/marc/projects/playground/pipeline/clsss.js:14
this.#hidden = !this.#hidden;
^
TypeError: Cannot read private member #hidden from an object whose class did not declare it
at Proxy.toggle (/home/marc/projects/playground/pipeline/clsss.js:14:30)
at Object.<anonymous> (/home/marc/projects/playground/pipeline/clsss.js:37:19)
at Module._compile (internal/modules/cjs/loader.js:1118:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1138:10)
at Module.load (internal/modules/cjs/loader.js:982:32)
at Function.Module._load (internal/modules/cjs/loader.js:875:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
重现代码:
class Parent {
#hidden;
constructor() {
this.#hidden = false;
}
get hidden() {
return this.#hidden;
}
toggle() {
this.#hidden = !this.#hidden;
console.log("Changed", this.#hidden)
return this.#hidden;
}
}
const p = new Parent();
const proxy = new Proxy(p, {
get: (target, prop, receiver) => {
return target[prop];
}
});
console.log(p.toggle())
console.log(proxy.toggle()) // this is the problem
console.log(p.toggle())
有没有办法处理代理类实例上的私有属性?
为什么这不适用于代理?
感谢您的任何提示/答案。
编辑:在github上发现了一个相关问题:https://github.com/tc39/proposal-class-fields/issues/106 https://github.com/tc39/proposal-class-fields/issues/106我发现的一个快速技巧是使用:
const proxy = new Proxy(..., {
get: (target, prop, receiver) => {
// bind context to original object
if (target[prop] instanceof Function) {
return target[prop].bind(p);
}
return target[prop];
}
});
但这似乎非常不干净/错误。
如果这是所需的行为,您可以将该方法绑定到构造函数上:
constructor() {
this.#hidden = false;
this.toggle = this.toggle.bind(this);
}
Demo:
class Parent {
#hidden;
constructor() {
this.#hidden = false;
this.toggle = this.toggle.bind(this);
}
get hidden() {
return this.#hidden;
}
toggle() {
this.#hidden = !this.#hidden;
console.log("Changed", this.#hidden)
return this.#hidden;
}
}
const p = new Parent();
const proxy = new Proxy(p, {
get: (target, prop, receiver) => {
return target[prop];
}
});
console.log(p.toggle())
console.log(proxy.toggle()) // this is the problem
console.log(p.toggle())
否则你可以代理类本身:
class Parent {
#hidden;
constructor() {
this.#hidden = false;
}
get hidden() {
return this.#hidden;
}
toggle() {
this.#hidden = !this.#hidden;
//console.log("Changed", this.#hidden)
return this.#hidden;
}
}
const p = new Parent();
const ParentProxy = new Proxy(Parent, {
get(target, prop, receiver) {
return target[prop];
}
});
const p2 = new ParentProxy();
console.log('p toggle:', p.toggle());
console.log('p2 toggle:', p2.toggle()); //
//console.log(proxy.toggle()) // this is the problem
console.log('p toggle:', p.toggle());
console.log('p2 toggle:', p2.toggle());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)