jQuery如何表现得像一个对象和一个函数?

js-*_*der 29 javascript jquery

jQuery$似乎是一个功能:

typeof $; // "function"
Run Code Online (Sandbox Code Playgroud)

它就像一个:

$('div').removeClass(); // $ constructs a new object with some methods like removeClass
Run Code Online (Sandbox Code Playgroud)

但是当我删除函数括号时,它的行为就像一个对象:

$.each(/* parameters */); // $ is an object with some methods like each
Run Code Online (Sandbox Code Playgroud)

我想知道这是如何可行的,以及如何将这种行为实现到我自己的函数中.

Rob*_*b W 33

函数也是对象,因此$.each可以以与Object类似的方式定义.

JavaScript是一种原型语言.对于jQuery,这意味着每个实例都$从中继承方法jQuery.prototype.见注释

一个非常粗略的演示,实现类似的行为:

(function() { // Closure to not leak local variables to the global scope
    function f(a, b) {
        //Do something
    }
    // Prototype. All properties of f.prototype are inherited by instances of f.
    // An instance of f can be obtained by:    new f, new f(), Object.create(f)
    f.prototype.removeClass = function(a) {
        return a;
    };
    function $(a, b) {
        return new f(a, b); // <--- "new f" !  
    } 
    $.each = function(a) {
        alert(a);             
    };
    window.$ = $; // Publish public methods
})();

//Tests (these do not represent jQuery methods):
$.each("Foo");                   // Alerts "Foo" (alert defined at $.each)
alert($().removeClass('Blabla'));// Alerts "Blabla"
Run Code Online (Sandbox Code Playgroud)

笔记

jQuery的root方法定义如下(仅显示相关部分):

(function(win) {
    var jQuery = function (selector, context) {
        return new jQuery.fn.init(selector, context, rootjQuery);
    };
    //$.fn = jQuery.fn is a shorthand for defining "jQuery plugins".
    jQuery.fn = jQuery.prototype = {
        constructor: jQuery,
        init: function( /* ..parameters.. */ ) { 
            //.... sets default properties...
        }
        //....other methods, such as size, get, etc...
        //.... other properties, such as selector, length, etc...
    };
    jQuery.fn.removeClass = function() { // (Actually via jQuery.fn.extend)
        // ... method logic...
    };  //...lots of other stuff...

    win.$ = win.jQuery = jQuery; //Publish method
})(window);
Run Code Online (Sandbox Code Playgroud)

prototype方法的优点是链接方法和属性非常容易.例如:

$("body").find("div:first").addClass("foo");
Run Code Online (Sandbox Code Playgroud)

实现此功能的方法可以是:

$.fn.find = function(selector) {
    ...
    return $(...);
};
Run Code Online (Sandbox Code Playgroud)

如果您对jQuery的实际实现感兴趣,请查看带注释的源代码:

  • @dotweb它的技巧是在`Constructor`中测试`this instanceof Constructor`.而且,如果不是,`return new Constructor(arg1,arg2);`.您可以在[他的博客](http://ejohn.org/blog/simple-class-instantiation/)上找到John Resig对此的总结.您还可以在[JS Perf](http://jsperf.com/optional-new-keyword)上找到许多与性能相关的变体. (2认同)
  • @dotweb对于我不完整的答案道歉,我必须快速前进.我刚刚完成了答案. (2认同)

rec*_*ive 10

所有功能都以这种方式工作

function fn() {
    alert("hi mom");
}

fn.foo = "bar";
Run Code Online (Sandbox Code Playgroud)