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 の実際の実装に興味がある場合は、注釈付きのソース コードをご覧ください。
- jQueryコア- コンストラクターと基本メソッドの定義。
jQuery.fn.extend
に慣れているremoveClass
jQueryに、などを追加する。- jQuery 1.7.1。