如何动态地改变一行JavaScript函数? [英] How can dynmically change a line of a JavaScript function?

查看:168
本文介绍了如何动态地改变一行JavaScript函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下功能:

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

现在在运行时我想更改alertMesg函数来做其他事情。我的想法是这样做。

Now at run time I would like to change the alertMesg function to do something else. My thought was to do somehting like this.

var temp = window.alertMesg.toString.replace("ok","great")
temp = temp.replace('function alertMesg()',"");
window.alertMesg = new Function(temp);

基本上,问题是我无法控制alertMesg函数中的源。我想改变这个功能,但实际上我不可能改变它的源代码,因为它是生成服务器端的。话虽如此,我需要它的行为不同。

Basically, the problem is I have no control over the source in the alertMesg function. I would like to change the function, but I can't actually change the source of it because it is produced server side. That being said, I need it to act differently.

PS:我忘了提一个重要的部分:我必须保留大部分的功能。我不能正确地替换功能。我必须保持95%的功能,并改变其他5%。

PS: I forgot to mention an important part: I have to keep most of the function. I can't just replace the function out right. I have to keep 95% of the function the way it is, and change the other five percent.

@Barlow Tucker,quixoto,pekka
谢谢,for兴趣。

@Barlow Tucker, quixoto, pekka Thanks, for the interest.

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

Basically, I don't think the proxy idea will work because I am not just adding functionality, I am changing the functionality of the code. I want for example, the third line of the function to be different. In my real life example I have to add a line right in the middle of a function.

推荐答案

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

If you must replace the content of a function, it is possible:

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!"

这可能不是您尝试实现的最佳方式,但我可以除非你提供更多的细节,否则真的建议别的。

This probably isn't the best way to do what you're trying to achieve, but I can't really suggest anything else unless you provide more details.

这篇关于如何动态地改变一行JavaScript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆