I want to slightly modify the code of some function, exposed to me by a third party module. I was thinking of copying the function and modifying it, but the problem is that it relies on other functions and variables that exist in its lexical scope. I do not have a problem with the infamous "this" binding, but with the scope itself.
For example, this is the third party library:
var someGlobalVar;
function someInnerFunction(){
//Does something...
}
function functionIWantToAlter(){
//I want to copy the implementation of this function, and alter parts of it,
// but i need to preserve its lexical scope.
const x=5;
const y=10;
console.log(x+y);
someInnerFunction(someGlobalVar)//The function calls some inner function, and uses an inner variable
}
module.exports = functionIWantToAlter;
Then, in my code, i want to literally copy this function, but to preserve its lexical scope:
const functionIWantToAlter = require('third-party-module');
//Maybe here it's somehow possible to "bind" my override function, to the lexical
//scope of "functionIWantToAlter"?
function override(){
//Do here something different, than the original function does
const x=1;
const y=2;
console.log(y*x);
someInnerFunction(someGlobalVar)//Some of the implementation is the same,
// but my code doesn't have access to the original lexical scope.
}
Is there a way this could be done?
Edit: The library i need to "patch" is node-fetch. This is the function: https://github.com/node-fetch/node-fetch/blob/master/src/index.js
In the npm_module itself the code comes in one big JS file, but i don't think it makes any difference. Any idea how to do it?