JQuery Custom function call with one $

(function ($) {
    $.fn.test = function () {
        console.log('works');
    };
})(jQuery);

$(document).ready(function () {
    var var1 = $().test(); // works
    var var1 = $.test(); // error: $.test is not a function
});

Can I call it that $.test()?

+5
source share
2 answers

You can easily expand the object itself. jQuery

(function ($) {
    $.test = function () {
        console.log('works');
    };
})(jQuery);

But keep in mind that this function will not be available in jQuery.fn(which is equal jQuery.prototype), and therefore you cannot access dom nodesthere through this, and you could not bind this method after or before other functions of the jQuery plugin.

The reason it works $().test()is because the jQuery constructor function creates a new object that is associated with jQuery.fn(prototype ..).

+3
source

, , jQuery init. , $ jQuery. , $() jQuery, test() .

$.fn.test();

+2

All Articles