Created
February 20, 2019 20:17
-
-
Save XoseLluis/b21d06407e1dc6384342093182e8e373 to your computer and use it in GitHub Desktop.
Creating JavaScript proxies that can be modified (replace the get trap logic)
This file contains hidden or 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
function modifiableProxyFactory(target){ | |
//initialize the proxy with a "transparent" trap | |
let coreGetTrapFunc = (target, property, receiver) => target[property]; | |
let handler = { | |
//the "get trap" checks if we want to set the trap, otherwise it invokes the existing trap | |
get: function(target, property, receiver){ | |
if (property === "setGetTrap"){ | |
console.log("setting a new get trap!"); | |
return function(getTrap){ | |
coreGetTrapFunc = getTrap; | |
}; | |
} | |
else{ | |
return coreGetTrapFunc(target, property, receiver); | |
} | |
} | |
}; | |
return new Proxy(target, handler); | |
} | |
//let's test it: | |
class Person{ | |
constructor(name){ | |
this.name = name; | |
} | |
sayHi(){ | |
return "Hello I'm " + this.name; | |
} | |
} | |
let p2 = new Person("Emmanuel"); | |
console.log(p2.sayHi()); | |
let proxiedP2 = modifiableProxyFactory(p2); | |
console.log("\n- After creating 'empty' proxiedP2"); | |
console.log(proxiedP2.sayHi() + "\n"); | |
//------------------------------------ | |
proxiedP2.setGetTrap(function(target, property, receiver){ | |
let it = target[property]; | |
if (typeof it != "function"){ | |
return it; | |
} | |
else{ | |
return function(){ | |
console.log(property + " called"); | |
return it.call(this, ...arguments); | |
} | |
} | |
}); | |
console.log("\n- After reassigning get trap"); | |
console.log(proxiedP2.sayHi() + "\n"); | |
//------------------------------------ | |
proxiedP2.setGetTrap(function(target, property, receiver){ | |
let it = target[property]; | |
if (typeof it != "function"){ | |
return it; | |
} | |
else{ | |
return function(){ | |
console.log(property + " CALLED!!!"); | |
return it.call(this, ...arguments); | |
} | |
} | |
}); | |
console.log("\n- After reassigning get trap again"); | |
console.log(proxiedP2.sayHi() + "\n"); | |
//-- output: | |
// Hello I'm Emmanuel | |
// - After creating 'empty' proxiedP2 | |
// Hello I'm Emmanuel | |
// setting a new get trap! | |
// - After reassigning get trap | |
// sayHi called | |
// Hello I'm Emmanuel | |
// setting a new get trap! | |
// - After reassigning get trap again | |
// sayHi CALLED!!! | |
// Hello I'm Emmanuel |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment