user2847819
user2847819

Reputation:

How do you access a function inside an anonymous function from outside

I am writing some useful functions for my webpage for my webpage. The functions will be inside an anonymous function and will be called from outside the function. When I try to call the functions I get an error. This is how I am constructing it:

(function(){
    var fx ={
        pop : function(msg){
            alert(msg);
        }
    };
    fx = window.fx;
})();
window.onload = fx.pop('hi');

Does anyone know how I might do this? I know this is possible because jQuery and other javascript libraries are written like that.

Upvotes: 2

Views: 1126

Answers (2)

PSL
PSL

Reputation: 123739

When you do fx = window.fx; you are overwriting the fx which is in local scope of anonymous function. If you want access to it outside in the global scope you would need to do window.fx = fx;. And Seems like you want to invoke the function pop on load and not when registering on load, Which is what you are trying to do here window.onload = fx.pop('hi'); This will invoke pop immediately and set the result of method as callback for load event (which is undefined as your method doesn't return anything; unless the method return another function that needs to be invoked after load this becomes useless). Instead you may want to try this way.

window.onload = fx.pop.bind(this, 'hi'); //Now this will get invoked only after load event is completed, it bind the current context to the function pop with the argument  `hi`

or

window.onload = function(){
    fx.pop('hi'); //Now this gets invoked only after load event is completed
};

So you can try:

(function(){
    var fx ={
        pop : function(msg){
            alert(msg);
        }
    };
    window.fx = fx;
})();
window.onload = function(){
    fx.pop('hi')
};

Upvotes: 1

Plato
Plato

Reputation: 11052

are you sure jquery and other javascript libraries are written like that? I don't know of a simple way to gain access to the scope of a function, from outside that function. this seems like an unusual objective so please explain what problem you are attempting to solve with this technique, perhaps there is a more appropriate strategy.

For instance you could try:

var fx;
(function(){
    fx ={
        pop : function(msg){
            alert(msg);
        }
    };
    fx = window.fx; // this will probably overwrite your previous object with undefined
})();
window.onload = fx.pop('hi');

Upvotes: 0

Related Questions