escodegen icon indicating copy to clipboard operation
escodegen copied to clipboard

Simple Helloworld to do a function rewrite using esparse and escodegen

Open reachbhargava opened this issue 9 years ago • 1 comments

Hello, my name is Bhargava and I am a student. I am trying to use esparse and escodegen in the browser directly to do a simple function rewriting so that the re-written function has the before-after logging added. Below is the code (directly on browser and no nodejs) function start() { console.log('start'); } function end() { console.log('end'); } function actualFunction() { console.log('actualFunction'); } var parsed = esprima.parse('actualFunction()') parsed.body.unshift(esprima.parse('start()')) parsed.body.push(esprima.parse('end()')) var newCode = escodegen.generate(parsed)

	myFunction = new Function(newCode);
	myFunction();

When I am invoking the myFunction() here, it works as expected. The start and end logs are printed with the actualFunction in between.

But since it is a function rewriting and I want to actually utilize this to rewrite a js library function, I would have to end up using the same name as the original for the overwritten function. So, if I replace the last 2 lines of the above code with the below lines, it goes to an infinite loop printing start.

            actualFunction = new Function(newCode);
	actualFunction ();

reachbhargava avatar Jan 12 '17 08:01 reachbhargava

myFunction = new Function(newCode); myFunction();

How did those two lines get executed in the first place? I got this error when I tried your code - screen shot 2017-07-12 at 9 13 25 am

GauthamBanasandra avatar Jul 12 '17 03:07 GauthamBanasandra