我想在对象上定义getter方法,以便在访问属性时触发getter方法

object.someProperty // this fires object.get(name) where name is someProperty




这是一个例子,说明了我的想法

文件: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;


文件: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

最佳答案

您可以查看Proxies



const data = {
    a : {
        foo : 1 ,
        bar : 2
    } ,
    b : {
        foo : 3 ,
        bar : 4
    }
}

const setting = {
  type: 'a'
};

const products = new Proxy({
     data: data
   },
   {
     get: function(obj, prop) {
       return obj.data[setting.type][prop];
     },
     set: function(obj, prop, value) {
       obj.data[setting.type][prop] = value;
     }
   });

console.log('Before type change');
console.log(products.foo);

setting.type = 'b';

console.log('After type change');
console.log(products.foo);

products.foo = 4;

console.log('After value change');
console.log(products.foo);

setting.type = 'a';

console.log('After type change');
console.log(products.foo);

10-08 11:11