var n = {
a: 1,
b: function() {
return Math.random();
}
}
如何以更简单的方式获取对象 n 中任何方法或变量的值?
现在我的解决方案是:
get = 'b';
typeof n[get] === 'function' ? n[get]() : n[get]; //returns a random number
get = 'a';
typeof n[get] === 'function' ? n[get]() : n[get]; //returns 1
是否需要检查类型以获取 n.a 或 n.b 的值?这些都不能满足自己的要求:
n[get] // fails to retrieve return value of n.b
n[get]() //throws an error retrieving value of n.a
答案 0 :(得分:2)
如果使用Object.create()
以不同方式定义对象,则可以为特定属性指定setter和getter:
o = Object.create(Object.prototype, {
a: { value: 1 },
b: {
configurable: false,
get: function() { return Math.random(); }
}});
console.log( o.a ); // just 1
console.log( o.b ); // random value
答案 1 :(得分:0)
根据mozilla's "get" page,在改进Sirko的答案之后,最简单的答案是:
var o = {
a: 1,
get b() {
return Math.random();
}
}
console.log( o.a ); // returns 1
console.log( o.b ); // random value
这消除了使用Object.create的需要。