2017-09-26 184 views
0

如何在JavaScript中执行函数覆盖?JavaScript中的函数覆盖

我有以下代码。

function helloWorld() { 
    return 'helloworld '; 
} 

var origHelloWorld = window.helloWorld; 

window.helloWorld = function() { 
    return 'helloworld2'; 
} 

alert(helloWorld); 

我想获得像

helloworld helloworld2

输出我该怎么办?

可能我描述的较少。其实我想打电话功能helloworld,我想共同输出这两个功能。

+0

呼叫从覆盖原始和结果追加到返回值。 – DarthJDG

+0

也可以在警报的参数中调用重写。 – Teemu

+1

你必须阅读关于JavaScript的原型,它可能会帮助你。 – sjahan

回答

1

试试这个:

function helloWorld() { 
    return 'helloworld '; 
} 

var origHelloWorld = window.helloWorld; 

window.helloWorld = function() { 
    return origHelloWorld() + ' ' +'helloworld2'; 
} 

alert(helloWorld()); 
+0

感谢@colxi的回复。如果我只想打印'helloworld helloworld2',你的回复是正确的。但这是一个例子。我想要在函数内部存在任何代码的情况下共同输出这两个函数。谢谢 –

+0

我不明白,你是什么意思? – colxi

0

你确定,你明白重写?

你的样品与帕尔玛相同,如何覆盖它?

和JavaScript没有关于覆盖的方法,但您可以用其他方式覆盖。你可以按照other questions in stackoverflow

0

使用闭包,以避免污染全局命名空间:

function helloWorld() { 
    return 'helloworld '; 
} 

helloWorld = (function() { 
    var original = window.helloWorld; 
    return function() { 
    return original() + ' helloworld2'; 
}})(); 

alert(helloWorld());