JavaScript中的函数覆盖

时间:2017-09-26 08:48:14

标签: javascript function override

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

我的代码如下。

function helloWorld () {
    return 'helloworld ';
}

var origHelloWorld = window.helloWorld;

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

alert(helloWorld);

我想获得像

这样的输出

helloworld helloworld2

我该怎么办?

可能是我描述的少了。实际上我想调用函数helloworld,我想联合输出两个函数。

3 个答案:

答案 0 :(得分:1)

试试这个:

function helloWorld () {
    return 'helloworld ';
}

var origHelloWorld = window.helloWorld;

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

alert( helloWorld() );

答案 1 :(得分:0)

您确定,您了解覆盖吗?

你的样本有相同的帕尔玛,如何覆盖它?

并且javascript没有关于覆盖的方法,但您可以通过其他方式覆盖。你可以关注other questions in stackoverflow

答案 2 :(得分:0)

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

function helloWorld () {
    return 'helloworld ';
}

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

alert(helloWorld());