Javascript 如何编辑函数而不重写其内容?

Javascript 如何编辑函数而不重写其内容?,javascript,Javascript,我有两个脚本,但无法访问其中一个。如何编辑函数的内容而不重写它 例如: 我知道这可以编辑功能: <script> function a() { alert('hi'); } </script> <script> function a() { alert('hi'); console.log('hi'); } </script> 函数a(){ 警报(“hi”); } 函数a(){ 警报(“hi”); console.log('hi'); } 但

我有两个脚本,但无法访问其中一个。如何编辑函数的内容而不重写它

例如:

我知道这可以编辑功能:

<script>
function a() {
alert('hi');
}
</script>
<script>
function a() {
alert('hi');
console.log('hi');
}
</script>

函数a(){
警报(“hi”);
}
函数a(){
警报(“hi”);
console.log('hi');
}

但是我不想再次重写“警报('hi')”

您可以窃取函数的符号,如下所示:

var b = a;             // <== Takes the original `a` and remembers it as `b`
a = function() {       // <== Assigns a new function to `a`
    var rv = b();      // <== Calls what used to be `a`, remembers its return value
    console.log("hi");
    return rv;         // <== Returns what the old function returned
};

尝试以下操作:将新函数设置为旧函数,然后重新分配旧函数:

function a() {
    alert('hi');
}
b = a;
a = function()
{
    b();
    console.log('hi');
}
a();

请注意,必须使用表达式分配新的
a
a=function()…
如果只执行
function a()…
,则会得到递归并超过最大调用堆栈大小。

另一个选项是通过搜索和替换重新定义函数源:

eval(a.toString().replace(/(alert\(\'hi\'\)\;)/,"$1\nconsole.log('hi');"));

您可以将原始函数序列化为字符串,构造新函数并将新行追加到其中:

function a() {
     alert('a');
}

var b = new Function('(' + a + ")(); alert('b');")

b(); // would alert twice, 'a' & 'b'

您使用哪个文本编辑器编辑此函数?是否要向函数添加功能?也就是说,你想做任何它已经做的事情,再加上一些其他的事情吗?只是写上它?
function a() {
     alert('a');
}

var b = new Function('(' + a + ")(); alert('b');")

b(); // would alert twice, 'a' & 'b'