Javascript 如何向所有对象添加getter

Javascript 如何向所有对象添加getter,javascript,getter-setter,Javascript,Getter Setter,如何向所有对象添加getter(或prototype/method)。 我有一个对象看起来像: foo.bar.text //or foo.bar.child.text text-是一个字符串数组,但我只需要其中一个。 每次我得到这个值时,我只想得到一个固定索引(这个索引保存在另一个变量中) 因此,我需要的结果是: foo.text = ['a','b'] foo.bar.text = ['c','d'] foo.bar.someChild.text = [null, undefined]

如何向所有对象添加getter(或prototype/method)。 我有一个对象看起来像:

foo.bar.text
//or
foo.bar.child.text
text
-是一个字符串数组,但我只需要其中一个。 每次我得到这个值时,我只想得到一个固定索引(这个索引保存在另一个变量中)

因此,我需要的结果是:

foo.text = ['a','b'] 
foo.bar.text = ['c','d']
foo.bar.someChild.text = [null, undefined]
x = 1;

// here we make some magic

console.log(foo.text) // b
console.log(foo.bar.text) // d
console.log(foo.bar.someChild.text) // undefined
所以,如果任何对象包含一个数组
text
,如果我们尝试获取它,我们将从中获取一些定义项,而不是数组

手动指向项目I不能,因此
foo.bar.text[x]
不是选项。 我们获取的数组和变量的名称是可选的,例如,我们可以将数组保存在
fullText
中,然后尝试获取
text
。好像
text=fullText[x]

有人能建议我如何实现这个,getter,setter,prototype吗

更新 代理似乎是我的选择,谢谢你的建议

我建议您递归地应用于
foo
对象

// the code is handwriting without test
var handler = {
  get: (target, prop) => {
    if (prop === 'text') {
       if (target[prop] instanceof Array) {
         return target[prop][x];
       } else {
         // dealing with non-array value
       }
    } else if (typeof target[prop] === 'object') {
       return new Proxy(target[prop], handler);
    } else {
       return target[prop];
    }
  }
}
var newFoo = new Proxy(foo, handler);

注意:
target[prop]
的类型如果
target[prop]
是数组,则将等于
的“object”