Home > Mobile >  How to catch a function into a variable and change its code?
How to catch a function into a variable and change its code?

Time:10-21

If a variable contains an existing function, how can you replace something inside its code?

It seems toString() (in order to replace the string) adds an "extra" function() { } and therefore fails.

For example changing test1 into test2 or test3 in:

var theparent = {
  myfunc: function () {
    console.log('test1');
  }
}

console.log(theparent.myfunc);
theparent.myfunc();
theparent.myfunc = new Function("console.log('test2')"); // Works
console.log(theparent.myfunc);
theparent.myfunc();
theparent.myfunc = new Function(theparent.myfunc.toString().replace('test2', 'test3')); // Adds function() { }
console.log(theparent.myfunc);
theparent.myfunc(); // Fails

CodePudding user response:

Maybe if you make the internal function an immediately called function, not a scalable solution though, but try this:

var theparent = {
  myfunc: function () {
    console.log('test1');
  }
}

console.log(theparent.myfunc.toString());
theparent.myfunc();
theparent.myfunc = new Function("console.log('test2')"); // Works
console.log(theparent.myfunc.toString());
theparent.myfunc();
theparent.myfunc = new Function("(" theparent.myfunc.toString().replace('test2', 'test3') ")()"); // Adds function() { }
console.log(theparent.myfunc.toString());
theparent.myfunc(); // Works

CodePudding user response:

The only thing that seemed to me (from this) was eval:

var theparent = {
  myfunc: function () {
    console.log('test1');
  }
}

console.log(theparent.myfunc);
theparent.myfunc();
theparent.myfunc = new Function("console.log('test2')"); // Works
console.log(theparent.myfunc);
theparent.myfunc();
eval("theparent.myfunc = "   theparent.myfunc.toString().replace('test2', 'test3')) // does NOT add function() { }
console.log(theparent.myfunc);
theparent.myfunc(); // Finally works

  • Related