tags:

views:

108

answers:

5

I have a javascript function (function1) that checks some global variables (can the user connect, is the service available, etc) before calling another (legacy) function (function2) that actually pops a window and connects the user to our service. I want to prevent function2 from being called anywhere but from function1. Is this possible?

As a cheap solution, I figured I could emit a variable from function1 and check for it in function2 before executing. Is there another way? Is there a way to find out the calling element/method in a javascript function?

A: 

Why not just remove function2, move its entire content into function 1 ?

Then you can just replace the old function 1 with something that signals the error.

krosenvold
+4  A: 

Read here: Crockford's method. Declare the function inside the first function.

jacobangel
+1  A: 

You should check this:

and this:

  • https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/caller
Tiago
A: 

you can move function2 inside of function1 so that's it's "private" to function1. check out the "module pattern".

ob
A: 
var function1 = function() {
    var function2 = function() { alert('hi'); };

    function2();
};

function1(); // alerts "hi";

function2(); // error function2 is undefined
Luca Matteis