如何动态地改变JavaScript函数的一行?

GC_*_*GC_ 5 javascript jsf dynamic

假设我有以下功能:

function alertMesg()
{
   alert("This ok function alerts message!");
}
Run Code Online (Sandbox Code Playgroud)

现在在运行时我想更改alertMesg函数以执行其他操作.我的想法是做这样的事情.

var temp = window.alertMesg.toString.replace("ok","great")
temp = temp.replace('function alertMesg()',"");
window.alertMesg = new Function(temp);
Run Code Online (Sandbox Code Playgroud)

基本上,问题是我无法控制alertMesg函数中的源.我想更改功能,但我实际上无法更改它的来源,因为它是生成服务器端.话虽如此,我需要采取不同的行动.

PS:我忘了提到一个重要的部分:我必须保留大部分功能.我不能只是正确地替换功能.我必须保持95%的功能,并改变其他百分之五.

@Barlow Tucker,quixoto,pekka谢谢,感兴趣.

基本上,我不认为代理的想法会起作用,因为我不只是添加功能,我正在改变代码的功能.我想要例如,函数的第三行是不同的.在我的现实生活中,我必须在函数中间添加一行.

Dum*_*Guy 7

如果必须替换函数的内容,则可以:

function alertMesg()
{
   alert ("This ok function alerts my message!");
}

alertMesg(); // alerts "This ok function alerts my message!"

// do whatever you want to the function here
var temp = alertMesg.toString();
temp = temp.replace('my', 'your');

// now replace the original function
alertMesg=new Function(temp.substring(temp.indexOf('{')+1,temp.lastIndexOf('}')));

alertMesg(); // alerts "This ok function alerts your message!"
Run Code Online (Sandbox Code Playgroud)

这可能不是你想要达到目标的最佳方式,但除非你提供更多细节,否则我无法提出任何其他建议.