Javascript 使用相同代码获取方法或变量的值
如何以更简单的方式获取对象n中任何方法或变量的值?Javascript 使用相同代码获取方法或变量的值,javascript,Javascript,如何以更简单的方式获取对象n中任何方法或变量的值? 现在我的解决方案是: var n = { a: 1, b: function() { return Math.random(); } } 是否需要检查类型以获取n.a或n.b的值?仅凭这两项都不够: get = 'b'; typeof n[get] === 'function' ? n[get]() : n[get]; //returns a random number get = 'a';
现在我的解决方案是:
var n = {
a: 1,
b: function() {
return Math.random();
}
}
是否需要检查类型以获取n.a或n.b的值?仅凭这两项都不够:
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
如果使用不同的方法定义对象,则可以为特定属性指定setter和getter:
n[get] // fails to retrieve return value of n.b
n[get]() //throws an error retrieving value of n.a
根据研究,在细化Sirko的答案后,最简单的答案是:
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
这样就不需要使用Object.create。使用
eval
:eval(“typeof”+n[get]+“==”函数“)?n[get]():n.get
是,需要检查类型。
var o = {
a: 1,
get b() {
return Math.random();
}
}
console.log( o.a ); // returns 1
console.log( o.b ); // random value