是否可以在 getter 创建中将变量转换为文字?

问题描述 投票:0回答:1

例如,如果我想将对象的每个属性拆分为普通值和

getter
,我不能使用 for in,因为 get 函数将是
return this["_" + i]
。我期望的是
i === "name"
-> 创建
getter
->
getter
返回
this._name
,但由于
"_" + i
仅在运行时进行评估,因此
getter
会查找
this["_" + i]

这意味着

getter
不能与任何类型的模块化对象一起使用。它们只能一一定义,并且不能使用除全局变量和它们所在对象的属性之外的任何变量。

有什么解决方法吗?我会使用函数构造函数,但没有地方可以使用它。

javascript getter
1个回答
0
投票

您可能可以使用代理来拥有动态 getter:

class Test{
  
  a = 1;
  b = 2;
  c = 3;
  
  constructor(){
    return proxify(this);
  }

}

const test = new Test;

for(const key in test){
  const val = test['_' + key];
}

function proxify(obj){

  return new Proxy(obj, {get(target, prop){
    if(prop[0] === '_'){
      console.log(`${prop} is invoked`);
      return target[prop.slice(1)];
    }
    return Reflect.get(...arguments);
  }});

}

© www.soinside.com 2019 - 2024. All rights reserved.