jQuery如何区分$()和$ .method调用?

时间:2016-02-02 16:34:59

标签: javascript jquery

查看较旧的jQuery版本的结构:

(function( window, undefined ) {

    var jQuery = (function() {

        var jQuery = function( selector, context ) {
            return new jQuery.fn.init( selector, context );
        };

        jQuery.fn = jQuery.prototype = {
            init: function( selector, context ) {
                // ...
                return this;
            }
            // jQuery API methods
        }

        // Give the init function the jQuery prototype for later instantiation
        jQuery.fn.init.prototype = jQuery.fn;

        return (window.jQuery = window.$ = jQuery);

    })();

})(window);

很容易理解:

jQuery.fn = jQuery.prototype = {
    init: function( selector, context ) {
        return this;
    }
}
jQuery.fn.init.prototype = jQuery.fn;

是在正常使用时调用jQuery时触发的一个部分,例如

$('p')

jQuery('p')

我们真的不清楚如何使用$.ajax()$.isArray()形式调用API方法,并且您会在列出的代码中放置一个自定义方法并将其调用$ .myCustomMethod()。 任何帮助将非常感谢。

1 个答案:

答案 0 :(得分:7)

你可以自己写一个函数:

function something(n) {
  return n + 1;
}

并称之为:

var x = something(0);

您还可以将属性附加到该函数,因为它是一个对象:

something.else = function(n) {
  return n - 1;
};

然后,您可以通过属性引用调用该函数:

var y = something.else(0);

jQuery库使用全局jQuery对象(通常称为$)作为放置一组通常有用但与集合中没有任何隐式关系的函数的地方。元素或对象是什么,各种jQuery"方法"做。一个明显的例子是$.ajax(),它非常有用,但它与DOM没有任何关系。

通过将所有这些功能保留为$的属性,库可避免"污染"全球地址空间。

相关问题