Last active
March 14, 2021 19:54
-
-
Save NovoManu/68143612a80c969c070f5f144744a145 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const target = {} | |
// Create proxy with no interceptors | |
const proxy = new Proxy(target, {}) | |
proxy.test = 5 | |
console.log(target.test) // Expected output: 5 | |
console.log(proxy.test) // Expected output: 5 | |
const arr = [1, 2, 3] | |
// Create proxy with interceptors | |
const handler = { | |
get(target, prop) { | |
// This interceptor will return default value if no value found | |
const defaultValue = 0 | |
return target[prop] || defaultValue | |
}, | |
set(target, prop, value) { | |
// This interceptor prevent adding no number values | |
if (typeof value === 'number') { | |
target[prop] = value | |
return true | |
} | |
return false | |
} | |
} | |
const proxyWithInterceptors = new Proxy(arr, handler) | |
console.log(proxyWithInterceptors[0]) // Expected output: 1 | |
console.log(proxyWithInterceptors[1]) // Expected output: 2 | |
console.log(proxyWithInterceptors[2]) // Expected output: 3 | |
console.log(proxyWithInterceptors[3]) // Expected output: 0 (default value) | |
proxyWithInterceptors.push(4) | |
console.log(proxyWithInterceptors[3]) // Expected output: 4 | |
proxyWithInterceptors.push('Hello World') // Error since string is pushed to the arr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment