如何为所有对象添加getter
How add getters to all objects
如何向所有对象添加 getters(或 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
,如果我们尝试获取它,我们获取的不是数组,而是其中的一些定义项。
我不能手动指向项目,所以 foo.bar.text[x]
不是一个选项。
我们得到的数组和变量的名称是可选的,例如我们可以将数组保存在 fullText
中并尝试获取 text
。好像text = fullText[x]
.
有人可以建议我如何实现这个,getter,setter,原型吗?
更新
代理似乎是我的选择,谢谢你的建议!
我建议您将 Proxy 递归地应用于 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);
如何向所有对象添加 getters(或 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
,如果我们尝试获取它,我们获取的不是数组,而是其中的一些定义项。
我不能手动指向项目,所以 foo.bar.text[x]
不是一个选项。
我们得到的数组和变量的名称是可选的,例如我们可以将数组保存在 fullText
中并尝试获取 text
。好像text = fullText[x]
.
有人可以建议我如何实现这个,getter,setter,原型吗?
更新 代理似乎是我的选择,谢谢你的建议!
我建议您将 Proxy 递归地应用于 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);