Coming from Java with experience in bytecode editing, I was wondering if I could change the bodies of functions at runtime with Javascript.
For this question, let's use the following code as example:
function myFunction(paramA, paramB) {
console.log('a', paramA);
console.log('b', paramB);
}
At runtime, I want to be able to change the body to:
function myFunction(paramA, paramB) {
console.log('a', paramA);
console.log('hello inserted world');
console.log('b', paramB);
}
If this is possible, I am aware of the complexity it will add to the codebase. And thus it should be avoided if possible within group projects (or when someone has to take over eventually), but that is not the question for now.
The real question is, is this possible (or can this be approximated) and how would one go about it? I am not looking for code examples, pseudo would be more than enough!
A few requirements/rules/notes:
- The example contains a function declaration, however a function expression would also be acceptable.
- The function may be fully overridden; existing references may be lost.
- The entire application will be minified, and the answer should account for this.
- The inserted code must be inserted right after the first
console.log
, regardless of any other code that may or may not be inside the body. - The function must be executable through
myFunction(a, b)
.