回答:
jQueryでは、fnプロパティはプロパティの単なるエイリアスprototypeです。
jQuery識別子(または$)だけでコンストラクタ関数コンストラクタのプロトタイプを継承し、それを作成したすべてのインスタンス。
簡単なコンストラクタ関数:
function Test() {
this.a = 'a';
}
Test.prototype.b = 'b';
var test = new Test();
test.a; // "a", own property
test.b; // "b", inherited property
jQueryのアーキテクチャーに似た単純な構造:
(function() {
var foo = function(arg) { // core constructor
// ensure to use the `new` operator
if (!(this instanceof foo))
return new foo(arg);
// store an argument for this example
this.myArg = arg;
//..
};
// create `fn` alias to `prototype` property
foo.fn = foo.prototype = {
init: function () {/*...*/}
//...
};
// expose the library
window.foo = foo;
})();
// Extension:
foo.fn.myPlugin = function () {
alert(this.myArg);
return this; // return `this` for chainability
};
foo("bar").myPlugin(); // alerts "bar"
function func1 (a) { ... }、パラメータは「a」変数であり、プロパティは「a」変数ですvar foo = {}; foo.a = 'a'。
jQuery.fnはの省略形として定義されていjQuery.prototypeます。ソースコードから:
jQuery.fn = jQuery.prototype = {
// ...
}
つまりjQuery.fn.jquery、のエイリアスでjQuery.prototype.jquery、現在のjQueryバージョンを返します。もう一度ソースコードから:
// The current version of jQuery being used
jquery: "@VERSION",
fn文字通りjqueryを指しprototypeます。
このコード行はソースコードにあります。
jQuery.fn = jQuery.prototype = {
//list of functions available to the jQuery api
}
しかし、背後にある実際のツールfnは、独自の機能をjQueryにフックするための可用性です。jqueryは関数の親スコープにthisなるので、jqueryオブジェクトを参照することに注意してください。
$.fn.myExtension = function(){
var currentjQueryObject = this;
//work with currentObject
return this;//you can include this if you would like to support chaining
};
これがその簡単な例です。2つの拡張を作成したいとします。1つは青い境界線を置き、もう1つはテキストの色を青にし、それらを連鎖させます。
jsFiddle Demo$.fn.blueBorder = function(){
this.each(function(){
$(this).css("border","solid blue 2px");
});
return this;
};
$.fn.blueText = function(){
this.each(function(){
$(this).css("color","blue");
});
return this;
};
これで、次のようなクラスに対してそれらを使用できます。
$('.blue').blueBorder().blueText();
(これは、異なるクラス名を適用するなどのcssで最適に行われることを知っていますが、これは概念を示すための単なるデモであることを覚えておいてください)
この答えは、本格的な拡張機能の良い例です。
eachあなたのサンプルコードでスキップすることはできませんか?$.fn.blueBorder = function(){ this.css("border","solid blue 2px"); return this; };罰金をうまくいく.css()要素を超えるalerady反復します。
css関数はコレクションごとにコレクションを自動的に反復するため、確かに可能です。これはthis、外側のオブジェクトがjqueryオブジェクトであり、内側のオブジェクトが要素自体を参照する場所の違いを示す例にすぎません。
我々はjQueryのソースコードでjQuery.fn = jQuery.prototype = {...}あるためjQuery.prototype、オブジェクトは、の値はjQuery.fn単に同じオブジェクトへの参照となりjQuery.prototype既に参照。
これを確認するために、それがjQuery.fn === jQuery.prototype評価するtrue(それを行う)かどうかを確認し、同じオブジェクトを参照する