hoz
hoz

Reputation: 571

Overwrite an existing JavaScript function

I have an existing global JavaScript function called GlobalAll(). This function is loaded on every page by default in the section. function GlobalAll(){alert("I am Global!");} This function doesn't return anything. On some of the pages, I want to redefine this function so it alerts "I am Local!" instead or doesn't alert at all. The function name needs to stay the same as it is complicated than just alerting something.

So, technically what we need is to rewrite/overwrite this global function and call it with the same name in specific pages.

Any solutions?

Upvotes: 0

Views: 3760

Answers (3)

Lajos Arpad
Lajos Arpad

Reputation: 76551

Let's support you have a javascript file called global.js. Inside that, you have a GlobalAll function:

function GlobalAll() {
    alert("I am Global");
}

let's suppose you have this html:

<html>
    <head>
        <script type="text/javascript" src="/js/global.js"></script>
    </head>
    <body>
    </body>
</html>

You are calling GlobalAll somewhere, so you must have something like:

<html>
    <head>
        <script type="text/javascript" src="/js/global.js"></script>
        <script type="text/javascript">
            GlobalAll();
        </script>
    </head>
    <body>
    </body>
</html>

this alerts I am Global. You need to override the function after it was initially defined, to make sure that your local function overrides the global and you need to override the function before you call it, to make sure that when it is called, the right instance is used:

<html>
    <head>
        <script type="text/javascript" src="/js/global.js"></script>
        <script type="text/javascript">
            function GlobalAll() {
                alert("I am Local");
            }
            GlobalAll();
        </script>
    </head>
    <body>
    </body>
</html>

Upvotes: 0

d0nut
d0nut

Reputation: 2834

You could define the specialized behaviour for GlobalAll on each individual page. Just make sure that the new definition comes after the old one and javascript should use the newer definition.

Upvotes: 0

Tom
Tom

Reputation: 7740

Since the DOM loads sequentially from top to bottom, just redefine it somewhere below where you originally defined it.

So:

<body>

<script src="something.js"></script> <!-- defines GlobalAll() -->
<script>    
  function GlobalAll() {
    alert('I am local');
  }
</script>

</body>

Upvotes: 3

Related Questions