我有与此类似的代码:
class A {
constructor() {
this._a = 1;
}
get [val]() {
if (val == 'a') {
return this._a;
}
}
}
以上代码无效,因为val
不存在。
我想从computed getter
中获取getter
名称并添加到变量val
,这样我就知道要访问的属性。
我该如何实现?
您不能使用普通的类语法和getters / setter方法来做到这一点。问题是您只能定义concrete getters。
为了定义用于拦截all调用的吸气剂,您需要使用a Proxy
class A {
constructor() {
this._a = 1;
}
}
const handler = {
get: function(obj, prop) {
if (prop == 'a') {
return obj._a;
}
return `getting "${prop}" instead of "a"`;
}
};
const instance = new A();
const p = new Proxy(instance, handler);
console.log(p.a);
console.log(p.b);
console.log(p._a);
如果您要“隐藏”某些字段,例如以下划线开头的任何内容,则可以执行以下操作:
class A {
constructor() {
this._a = 1;
this._b = 2;
this._c = 3;
}
}
const handler = {
get: function(obj, prop) {
const secretProp = `_${prop}`;
//check if a property that starts with underscore is in the source object
if (secretProp in obj) {
return obj[secretProp];
}
return `getting "${prop}" is not allowed`;
}
};
const instance = new A();
const p = new Proxy(instance, handler);
console.log(p.a);
console.log(p.b);
console.log(p.c);
console.log(p._a);
console.log(p._b);
console.log(p._c);
console.log(p.foo);
欢迎使用堆栈溢出!
您正在寻找的是代理。普通类不能扩展这些代理,但是您可以确保类将自己实例化为代理。像这样
class A {
constructor() {
this._a = 1;
return new Proxy(this, {
get: (object, key, proxy) => {
if (key == 'a') {
return object._a;
}
}
});
}
}
let someInstance = new A();
console.log(someInstance.a);