Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery. Call custom function with single $

Tags:

jquery

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

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

Is it possible to call like this $.test()?

like image 221
Tuco Ramirez Avatar asked Feb 09 '12 11:02

Tuco Ramirez


1 Answers

You could easily extend the jQuery object itself

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

But be aware that this function will not be available in jQuery.fn (which equals jQuery.prototype) and therefore, you can't access dom nodes in there via this, neither could you chain that method after or before other jQuery plugin functions.

The reason why $().test() works is, that the jQuery constructor function creates a new object which is linked to jQuery.fn (prototype..).

like image 141
jAndy Avatar answered Oct 05 '22 22:10

jAndy