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.

3
  • Call the original from your override and append the result to the return value. Commented Sep 26, 2017 at 8:49
  • And also call the overridden in alert's argument. Commented Sep 26, 2017 at 8:50
  • 1
    You must read about prototypes in javascript, it'll probably help you. Commented Sep 26, 2017 at 8:51

3 Answers 3

1

Try this:

function helloWorld () {
    return 'helloworld ';
}

var origHelloWorld = window.helloWorld;

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

alert( helloWorld() );
Sign up to request clarification or add additional context in comments.

2 Comments

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
i don't understand, what do you mean?
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

Comments

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.