Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access private members of jQuery plugin

jQuery plugins use a pattern like this to hide private functions of a plugin:

(function ($) {
    var a_private_function = function (opts) {
        opts.onStart();
    }

    $.fn.name_of_plugin = function (options) {
        a_private_function(opts);
    }
})(jQuery);

jQuery then makes those fn functions available like this:

some_callback = function() {};

jQuery('selector').name_of_plugin( { onStart: some_callback } );

Now I'd like to override a_private_function. Is there any way I can access it without patching the actual plugin code?

I thought maybe I could access the execution context of the private function by using caller but that did not work:

some_callback = function() {
    console.log(some_callback.caller.a_private_function); // -> undefined
};

jQuery('selector').name_of_plugin( { onStart: some_callback } );
like image 733
AndreKR Avatar asked Nov 03 '10 12:11

AndreKR


2 Answers

As I learned in this answer, the only way to access the private members of a jQuery plugin are to modify the plugin source itself.

like image 191
justkt Avatar answered Oct 13 '22 11:10

justkt


What you have there is a classical example of a closured function.

a_private_function is a function which is only visible within the scope from the "outer" anonymous function. Because of closure, the anonymous function assigned to name_of_plugin has access to the outer context and therefore a_private_function.

This is a good thing since you can protect and hide some of functions and variables.

Short story, there is absolutly zero chance to access a closured variable from the outside.

like image 24
jAndy Avatar answered Oct 13 '22 10:10

jAndy