1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| const sharedPropertyDefinition = { enumerable: true, configurable: true, get: null, set: null }
function proxy(target, sourceKey, key) { sharedPropertyDefinition.get = function proxyGetter() { console.log('han) return this[sourceKey][key] } sharedPropertyDefinition.set = function proxySetter(val) { this[sourceKey][key] = val } Object.defineProperty(target, key, sharedPropertyDefinition) }
function Data() { this.data = { a: 1, b: 2 }
for(let key in this.data) { proxy(this, 'data', key) } }
let data = new Data() console.log(data.a , data.b) // 1 2
data.a = 10 data.b = 20 console.log(data.a , data.b) // 10 20
|