我正在尝试简化 javascript 对象内容的创建,以便值取决于成员名称,如下所示:
var obj = {
1: "you selected 1",
2: "wow, you selected 2",
3: "this time, you selected " + myName(), //myName() gets resolved to 3
137: "I think you've chosen " + myName() + " this time.", //myName() gets resolved to 137
513: myName() + " is the answer!" //myName() gets resolved to 513
};
是否有可能在值的定义中反向引用成员名称,使用类似假定函数 myName() 的方法?
如果不存在本地方法,推荐的方法是什么?
你可能会问“为什么这家伙需要这种奇怪的方式来生成对象?”,答案是:在我的代码中,成员/字段名称可能会改变,默认值会被复制唯一的区别是对成员名称的引用,我不想在每个键值对中定义数字值两次,因此我采用了一种在值定义中反向引用名称的方法。
最佳答案
您正在寻找 ES6 功能,Proxy
The
Proxy
object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).
然后使用实际 key 获取 prop
并将占位符 {key}
替换为实际 key 。
var obj = {
1: "you selected {key}",
2: "wow, you selected {key}",
3: "this time, you selected {key}",
137: "I think you've chosen {key} this time.",
513: "{key} is the answer!"
},
p = new Proxy(obj, {
get: function(target, prop) {
return target[prop] && target[prop].replace("{key}", prop);
}
});
console.log(p[3]); // this time, you selected 3
console.log(p[137]); // I think you've chosen 137 this time.
console.log(p[513]); // 513 is the answer!
obj.foo = 'This is {key}!'; // create new property foo
console.log(p.foo); // This is foo!
obj.bar = obj.foo; // assign foo to bar
delete obj.foo; // delete foo
console.log(p.foo); // undefined
console.log(p.bar); // This is bar!
关于Javascript 对象 : backreference to property name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41307235/