我想在对象上定义 getter 方法,这样当我访问属性时,getter方法会触发
object.someProperty // this fires object.get(name) where name is someProperty
这是一个说明我的想法的例子
file:data.js
import setting from 'setting';
const data = {
a : {
foo : 1 ,
bar : 2
} ,
b : {
foo : 3 ,
bar : 4
}
}
//DEFINE GETTER
//something like this
data.DEFINE_GETTER(function(property)
{
if(setting.type === 'a')
return data['a'][property];
else
return data['b'][property];
})
export default data;
file:test.js
import data from 'data';
import setting from 'setting';
setting.type = 'a';
console.log(data.foo) //should be 1
console.log(data.bar) //should be 2
setting.type = 'b';
console.log(data.foo) //should be 3
console.log(data.bar) //should be 4
答案 0 :(得分:1)
您可以定义getter
Object.defineProperty(data, 'foo', {
get: function() { return this[setting.type].foo }
});
Object.defineProperty(data, 'bar', {
get: function() { return this[setting.type].bar }
});
修改强>
您可以将defineProperty
重构为迭代data
function defineDataProp( obj, setting )
{
Object.keys(Object.values( obj )[0]).forEach( function(key){
Object.defineProperty(obj, key, {
get: function() { return this[setting.type][ key ] }
});
})
}
<强>演示强>
const data = {
a : { foo : 1 , bar : 2 } ,
b : { foo : 3 , bar : 4 }
};
var setting = { "type" : "a" };
defineDataProp( data, setting );
setting.type = 'a';
console.log(data.foo,data.bar)
setting.type = 'b';
console.log(data.foo,data.bar)
function defineDataProp( obj, setting )
{
Object.keys(Object.values( obj )[0]).forEach( function(key){
Object.defineProperty(obj, key, {
get: function() { return this[setting.type][ key ] }
});
})
}
&#13;
答案 1 :(得分:1)
使用代理处理程序
let handler = {
get(target, propKey, receiver) {
console.log('get ' + propKey);
if(setting.type === 'a')
return data['a'][propKey];
else
return data['b'][propKey];
}
};
let proxyData = new Proxy(data, handler);
// now you can call
proxyData.foo
proxyData.bar