Suppose I have a function that modifies an object's method:

var obj = { // some code addBefore : function(method,func){ //some code this.before[method].push(func); this[method] = function(){ this.before[method].forEach(function(key){key();}); this.old[method].call(this); } } 

And then you need to cut a piece of code from the modified method. Original:

  function method(x){ var result = x*25; return result; } 

Due to the fact that I "modify" the function artificially, I need a function that transforms this method into the form:

  function method(x){ this.before[method].forEach(function(key){key();}); var result = x*25; return result; } 

And not in the form:

  this[method] = function(){ this.before[method].forEach(function(key){key();}); this.old[method].call(this); } 

those. Just need a function that takes as input a different function (f) and a string, deletes / replaces / adds a string in the function and returns a new function (f1).

  • You have nothing in common between the first function and the second. Please explain why you want to do this? - Stepan Kasyanenko
  • Changed the description of the problem. - Frog
  • I can’t just memorize the old function. there are still addAfter and addAround methods that also change the method. - Frog
  • It became even less clear. Try to show what you want to achieve. How will you use it. - Stepan Kasyanenko

1 answer 1

You can use serialization to get data as a string, and then use the eval () function. For example:

 function Foo(){alert('Hello, world!');} Foo(); // Hello, world! var newFoo = Foo.toString().replace('world', 'all'); eval(newFoo); Foo(); // Hello, all! 

A similar question with the use of nested functions was discussed in the https://stackoverflow.com/a/51123745/3941340 branch.