Skip to content

Instantly share code, notes, and snippets.

@max8hine
Last active November 26, 2018 03:40
Show Gist options
  • Save max8hine/52fca396c5eaf0028f086ed534794a55 to your computer and use it in GitHub Desktop.
Save max8hine/52fca396c5eaf0028f086ed534794a55 to your computer and use it in GitHub Desktop.
ES6 Proxies Object
const log = console.log
// https://www.youtube.com/watch?v=_5X2aB_mNp4
const Undefined = new Proxy(function() {}, {
// if call Undefined as function, you will get Undefined
get(target, key, receiver) {
return Undefined;
},
apply() {
return Undefined;
},
})
function seatBelt (obj) {
return new Proxy(obj, {
get(target, key) {
// Check does this property actually exist
const accessedProperty = Reflect.get(target, key)
if (typeof accessedProperty === 'object') return seatBelt(accessedProperty)
else if (accessedProperty == undefined) return Undefined
return accessedProperty
},
})
}
// Example - missing value handler
const handler = {
get (target, key) { return key in target ? target[key] : 'could not found' }
}
const obj2 = new Proxy({}, handler)
obj.a = 1
obj.b = 2
log(p.a, p.b)
log('c' in p, p.c)
// Example - validater
const validator = {
set: function(obj, prop, value) {
if (prop === 'age') {
if (typeof value !== 'number' || Number.isNaN(value)) {
console.log('Age must be a number')
// return error
}
if (value <= 0) {
console.log('Age must be a positive number')
// return error
}
obj[prop] = value
return true
}
}
}
let person = new Proxy({}, validator)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment