在 JavaScript 或 jQuery 中将代码动态附加到函数的末尾

Dynamically append code to end of a function in JavaScript or jQuery

本文关键字:函数 动态 JavaScript jQuery 代码      更新时间:2023-09-26

我有一些html的JavaScript。可以在以下 URL 中找到示例演示:http://js.do/sun21170/92329

我雄心勃勃的目标是在函数doSomething if else部分之后执行一些代码。我无法控制此函数内部的内容,因为它位于我使用的库中,但我确实想在此函数中执行最后一行代码后执行一些代码。 所以,这就像我想在函数的末尾动态插入一些 JavaScript 代码doSomething

问题:是否可以在函数的最后一行代码之后动态插入一些代码doSomething如果是,那么我将如何操作?

例如,我想插入以下自定义代码行:alert(val);或者如果访问变量是毫无疑问的,那么只需插入一些其他自定义代码,如 alert("hello"); .我尝试获取回调函数的主体,然后我想我可以附加我的新代码,但仍然无法实现我非常通用的要求。

<button type="button" onclick="callback(200);">Callback gets called </button>
<script>
var callback = null;
//the function below cannot be changed
function doSomething(val) {
    if (val > 150) {
        alert("You are not eligible for this reward");
    } else {
        alert("Congrats! You have just been rewarded");
    }
}

//set callback to something
callback = doSomething;
//I want to automatically execute some code when callback finishes execution without 
//having to explicitly write that code within the doSomething function OR
//writing code after doSomething function is called in onclick function of button
//If this is possible, HOW WOULD I IMPLEMENT THIS?

//I can get the body of a function using below code
function getCallBackBody(callbackFunction) {
    var entire = callbackFunction.toString();
    var body = entire.substring(entire.indexOf("{") + 1, entire.lastIndexOf("}"));
    return body;
}
</script>

您可以将 doSomething 替换为调用 doSomething 然后调用代码的函数。 确保首先定义 doSomething。

function doSomething(val) {
  if (val > 150) {
    alert("You are not eligible for this reward");
  } else {
    alert("Congrats! You have just been rewarded");
  }
}
var orig_doSomething = window['doSomething'];
window['doSomething'] = function () {
  orig_doSomething.apply(null, arguments);
  // your code, or a call to your function
  alert("Wow, doSomething just finished executing with these arguments - " + JSON.stringify(arguments));
};
<button type="button" onclick="doSomething(200);">Callback gets called </button>

可以用new Function(newBody)创建新函数,但这是非常非常可怕的解决方案。如果可能的话,不要这样做。

您可以使用函数构造函数使用新主体构造函数,如下所示:

function injectToCallback(callbackFunction, newBody) {
  var entire = callbackFunction.toString();
  var args = entire.match(/^function.+'((.+)')/);
  var body = entire.substring(entire.indexOf("{") + 1, entire.lastIndexOf("}")) + newBody;
  return new Function(args ? args[1] : "", body);
}

但是,您应该注意到这是某种 eval,因此请确保您不要传递第三方事物(即用户)提供的数据。

我不建议使用它。