Access private members of jQuery plugin

后端 未结 3 835
南方客
南方客 2020-12-19 08:19

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

(function ($) {
    var a_private_function = function (opts) {
        opts.onS         


        
相关标签:
3条回答
  • 2020-12-19 08:40

    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.

    0 讨论(0)
  • 2020-12-19 08:43

    When using the JQUERY UI widget factory, the functions (which are prefixed with _) are not private, but instead (simulated) protected (prototype) functions.

    This means you can access them as long as you extend the existing prototype. For example:

    $.extend( $.ui.accordion.prototype, {
        open: function( index ) {
            //now you can access any protected function
            var toOpen = self._findActive( index );
            toOpen.next().show();
         },
         _completed: function ( cancel ) {
             //You can even overwrite an existing function
    
         }
    });
    

    The function you have demonstrated in your first example is, however, private - and therefore as the other answers suggest you cannot access these from the outside.

    However, if you want to access protected variables inside a JQuery UI widget then this is possible (as above).

    Thought this might be useful.

    0 讨论(0)
  • 2020-12-19 09:07

    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.

    0 讨论(0)
提交回复
热议问题