Calling a function in JavaScript without parentheses

前端 未结 7 1644
醉梦人生
醉梦人生 2020-12-09 07:27

Is there a way in JavaScript to call a function without parentheses?

For example in jQuery:

$(\'#wrap\').text(\"asdf\"); will work and so will <

7条回答
  •  温柔的废话
    2020-12-09 07:51

    The difference in those examples is that .text() is a function on jQuery objects (instances of them, wrappers of elements), it's on $.fn (jQuery's prototype shortcut) so it's specifically for jQuery objects.

    $.ajaxSetup() is a method on the jQuery object/variable itself.

    If you look at the API it's easy to tell which methods are where, the jQuery.something() methods are methods on the jQuery variable/object, not related to an element set, everything else that's just .something() are the methods to run against element sets (on jQuery object instances).

    For what you want to do, yes it is possible, but it doesn't make much sense, for example:

    $.myFuntion = $.fn.myFunction = function() { alert('hi'); };
    

    You should place your methods where it makes sense, if it's for a set of elements, use $.fn.myFunction and this refers to the set of elements inside. If it's a static method unrelated to an element set place it outside separately or possibly at $.myFunction.

提交回复
热议问题