jQuery が返すオブジェクトは、DOM オブジェクトではなく、jQuery オブジェクトです。これらには DOM オブジェクトのコレクションが含まれていますが、jQuery はメソッドを DOM オブジェクトに直接追加することはまったくありません。jQuery.fn
は、jQuery によって返されるオブジェクトのプロトタイプへの単なる参照であり、そのプロトタイプにメソッドを直接追加できます。
jQuery の動作を再現することに興味があるので、同じことができます。ネイティブ DOM オブジェクトを独自のクラスでラップし、必要なメソッドをそのラッパー クラスに追加します。jQuery インスタンスで任意の DOM オブジェクト メソッドだけを呼び出すことはできないことに注意してください。jQuery は、実際の DOM メソッドを呼び出すためのユーティリティ メソッドをいくつか定義していますが、他の多くの DOM メソッドを呼び出すには、jQuery インスタンス内にラップされた実際の DOM オブジェクトにアクセスする必要があります。カスタム ラッパー クラスにも同じ制限があります。呼び出しを基になる DOM オブジェクトに転送するメソッドをラッパーに実装する必要があります。
例:
function DOMWrapper(domObject) {
this.domObject = domObject;
}
DOMWrapper.prototype = {
constructor: DOMWrapper,
foo: function(arg1, arg2, arg3) {
// this.domObject refers to the wrapped object here
this.domObject.nativeMethod();
// you could do things like this here:
return this.bar.call(this.domObject, arg1, arg2, arg3);
},
bar: function(arg1, arg2, arg3) {
// now, even though "bar" is defined as a method of
// the DOMWrapper prototype, it has been invoked by "foo"
// in the context of the wrapped DOM object, so
// "this" refers directly to the DOM object in this method
// this goes to the actual DOM nativeMethod:
return this.nativeMethod();
},
domMethodWrapper: function() {
return this.domObject.nativeMethod();
}
}