Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to a function declared within an anonymous function?

Tags:

javascript

I have a file called bbUI.js which contains this bit of JavaScript. Outside of that file, I'd like to be able to call "var x = new iScroll(...)", but I currently get the error "ReferenceError: Can't find variable: iScroll".

(function(){
var iScroll = function (el, options) {
        var that = this,
            doc = document,
            i;

        // More code
    };
})();

From what I can tell, iScroll is defined within an anonymous function, and is itself anonymous but assigned to the identifier iScroll. If that's accurate, should I be able to call "var x = new iScroll(...)" in other places in my code?

like image 221
yllus Avatar asked Mar 17 '26 07:03

yllus


2 Answers

The iScroll function only exists within the scope of the anonymous function it's wrapped in. To use it elsewhere, you need to make it global.

You can make it global by removing the function it's wrapped in, or by setting window.iScroll = iScroll inside the anonymous function.

like image 157
Rocket Hazmat Avatar answered Mar 18 '26 22:03

Rocket Hazmat


Remove the anonymous function that wraps the code:

(function(){   // <- this
  ...
})();          // <- this

The anonymous function prevents that code from polluting the global variables, so iScroll is defined only within that anonymous function.

like image 37
Blender Avatar answered Mar 18 '26 20:03

Blender