我正在尝试简化
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()一样的思考?
如果不存在本机方法,建议的方法是什么?
您可能会问“为什么这个人需要这种生成对象的方法?”,答案是:在我的代码中,成员/字段名称可能会更改,默认值将被复制,唯一的区别是对成员的引用name,我不想在每个键值对中定义数值两次,因此我采用了一种在值定义中反向引用名称的方法.
最佳答案 您正在寻找ES6功能,
Proxy
The
Proxy
object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).
然后使用实际键获取prop,并用实际键替换占位符{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!