Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

javascript - 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 } );
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...