Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call a specific javascript function when multiple same name function are in memory

Tags:

javascript

I need to call specific js function. The problem is many time runtime situation can come where another js file may contain same name function. But i need to be specific that which function i am suppose to call. Function overloading is not my solution.

Thanks and regards, Tanmay

like image 966
Tanmay Avatar asked Aug 17 '10 13:08

Tanmay


People also ask

What happens if we have two functions with same name in JavaScript?

JavaScript supports overriding not overloading, meaning, that if you define two functions with the same name, the last one defined will override the previously defined version and every time a call will be made to the function, the last defined one will get executed.

Can you call the same function within a function JavaScript?

Calling a function from within itself is called recursion and the simple answer is, yes.

How do you call a function within a function in JavaScript?

To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.

Can you call a function multiple times in JavaScript?

In order to run a function multiple times after a fixed amount of time, we are using few functions. setInterval() Method: This method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed.


1 Answers

you're going to have to do some reorganization of your resources and use namespacing where you can.

if you have a method named saySomething defined twice, you would move one of them to an object (whichever suits your needs better).

var myNS = new (function() {

    this.saySomething = function() {
        alert('hello!');
    };

})();

and the other defintion can be moved into a different object or even left alone.

function saySomething() {
    alert('derp!');
}

you can now call the saySomething method like

saySomething();      // derp!
myNS.saySomething(); // hello!

edit: since it was brought up in comments, this

var myNS = {
    saySomething: function() {
        alert('hello!');
    }
};

is equivalent to the first code block, in simpler form (if i'm remembering correctly).

like image 89
lincolnk Avatar answered Oct 02 '22 20:10

lincolnk