0

How to do function override in JavaScript ?

I have below code.

function helloWorld () {
    return 'helloworld ';
}

var origHelloWorld = window.helloWorld;

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

alert(helloWorld);

I would like to get output like

helloworld helloworld2

What should I do ?

May be I described less. Actually I would like to call function the helloworld and I would like to get output of both functions jointly.

abu abu
  • 6,599
  • 19
  • 74
  • 131

3 Answers3

1

Try this:

function helloWorld () {
    return 'helloworld ';
}

var origHelloWorld = window.helloWorld;

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

alert( helloWorld() );
colxi
  • 7,640
  • 2
  • 45
  • 43
  • Thanks @colxi for your reply. Your reply is correct if I only would like to print 'helloworld helloworld2'. But this is an example. I would like to get output of both function jointly whatever code is exists inside the functions. Thanks – abu abu Sep 26 '17 at 09:03
  • i don't understand, what do you mean? – colxi Sep 26 '17 at 12:02
0

Are you sure, you understand override?

yours sample with the same parma, how to override it?

and javascript has not a method about the override, but you can override in other ways. you can follow other questions in stackoverflow

Carson
  • 152
  • 11
0

Using closures to avoid polluting the global namespace:

function helloWorld () {
    return 'helloworld ';
}

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

alert(helloWorld());