如何在私有对象上设置特定属性 [英] How to set a specific property on a private object
问题描述
我希望能够通过为值提供 not 表示法路径来在 private 对象上设置属性.困难在于这个对象在闭包内,所以我不能直接访问它来以正常方式设置值(例如 dot.notation.path = 'new value'
).这看起来很奇怪,但我想不出明显的方法.
I want to be able to set a property on a private object by giving the not notation path to the value. The difficulty is that this object is within closure so I can't access it directly to set the value the normal way (eg. dot.notation.path = 'new value'
). This seems weird but I can't think of the obvious way.
示例:
// setter function
function set(path, change){
var privateObject = {
a: 'a',
b: 'b',
c: {
d: 'd',
e: 'e'
}
}
privateObject[path] = change;
return privateObject;
}
// execution
var result = set('c.d', 'new value');
// desired result
//{
// a: "a"
// b: "b"
// c: {
// d: "new value",
// e: 'e'
// }
//}
// actual result
//{
// a: "a"
// b: "b"
// c: {
// d: 'd',
// e: 'e'
// }
// c.d: "new value"
//}
工作示例:
[更新] 替代示例:
推荐答案
你真的很接近,但括号表示法不会为你处理点(它不能 —点是完全有效的属性字符名称).你必须自己做:
You're really close, but the bracket notation won't handle dots for you (it can't — the dots are perfectly valid characters for property names). You have to do that yourself:
function set(path, change){
var privateObject = {
a: 'a',
b: 'b',
c: {
d: 'd',
e: 'e'
}
},
index,
parts,
obj;
parts = path.split(".");
obj = privateObject;
if (parts.length) {
index = 0;
while (index < parts.length - 1) {
obj = obj[parts[index++]];
}
obj[parts[index]] = change;
}
return privateObject;
}
我认为它在旧引擎上并不是非常高效,我也没有费心去探索故障模式,但是你明白了:分割你在点上给出的路径,然后使用每个组成部分页面.
I dashed that off, it's not hyper-efficient on older engines and I didn't bother to explore failure modes, but you get the idea: Split the path you're giving on the dot, then use each component part of the page.
这篇关于如何在私有对象上设置特定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!