I've run into a situation wherein it might be beneficial to throw an error wherever a particular function is called in a JavaScript program. By which, I don't mean a reference to the function, but any and all references to the function, i.e., the function itself.
let doThing = ()=>console.log("Hello, world!");
// refer to the thing doThing refers to
let a = doThing;
// change what doThing refers to
doThing = ()=>{throw new Error()}; // This won't work for my use case
// "Hello, world!"
a(); // Because a still points to the working function
let b = a;
// kill what a points to
killFunctionSymbol(a); // Instead, I want something like this
// After which, everything fails...
a(); // Error
b(); // Error
I've read elsewhere that it's impossible to mutate the body of a function. But, in my case, I'm not sure I need to mutate the body. I just need the call to error. Is there any way I can achieve this? Is there some way I can alter the prototype such that it always breaks?
I think what you want is a Proxy. I have to say I'm always on the lookout to use proxies so this is a perfect use case.
Here is a very basic implementation of a proxy that hijacks the call to a function based on some external value
const doThing = (arg1, arg2) => `Hello World! ${arg1} ${arg2}`;
let killSwitch = false;
const handler = {
apply: function(target, thisArg, argumentsList) {
if (killSwitch) {
throw new Error('Kill switch engaged');
}
return target(...argumentsList);
}
};
const regular = doThing;
const withProxy = new Proxy(doThing, handler);
console.log(regular('foo1', 'bar1'));
console.log(withProxy('foo2', 'bar2'));
killSwitch = true;
console.log(withProxy('foo3', 'bar3'));
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
Hope this helps.