Created
November 17, 2020 23:20
-
-
Save gdhardy1/690e230a33a04ea153ca3912a274f9f2 to your computer and use it in GitHub Desktop.
JS Proxy
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
// Example of Proxy in JS | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy | |
class Target{ | |
log(msg){ | |
console.log(msg) | |
return msg | |
} | |
} | |
const target = new Target() | |
const handler = { | |
get: (target, name, receiver)=>{ | |
return (...args)=>{ | |
if (typeof target[name] === 'function') { | |
console.log(`Proxied! ${target[name](...args)}`) | |
}else{ | |
return Reflect.get(target, name, receiver) | |
} | |
} | |
} | |
} | |
const myProxy = new Proxy(target, handler) | |
// myProxy.log("This") | |
// myProxy.log(1) | |
const validator ={ | |
get: (target, name, receiver)=>{ | |
return (...args)=>{ | |
if(name === "log" && typeof(args[0]) !== String ){ | |
console.log(`Error: Must provide a string!`) | |
} | |
} | |
} | |
} | |
const validatedProxy = new Proxy(myProxy, validator) | |
validatedProxy.log("asdfasd") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment