jQuery はどのようにしてオブジェクトや関数のように動作するのでしょうか? 質問する

jQuery はどのようにしてオブジェクトや関数のように動作するのでしょうか? 質問する

jQueryまたは$関数のようです:

typeof $; // "function"

そしてそれは次のように動作します:

$('div').removeClass(); // $ constructs a new object with some methods like removeClass

しかし、関数の括弧を削除すると、オブジェクトのように動作します。

$.each(/* parameters */); // $ is an object with some methods like each

これがどのように可能なのか、またこの動作を自分の関数にどのように実装できるのかを知りたいです。

ベストアンサー1

関数もオブジェクトなので、$.eachオブジェクトと同様の方法で定義できます。

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"

ノート

jQuery のルート メソッドは次のように定義されています (関連する部分のみを示しています)。

(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);

この方法の利点prototypeは、メソッドとプロパティを連鎖させるのが非常に簡単なことです。例:

$("body").find("div:first").addClass("foo");

この機能を実装する方法は次のようになります。

$.fn.find = function(selector) {
    ...
    return $(...);
};

jQuery の実際の実装に興味がある場合は、注釈付きのソース コードをご覧ください。

おすすめ記事