| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -1,4 +1,4 @@ | |||
| 1 | - # jQueryのPlugin | ||
| 1 | + # jQuery | ||
| 2 | 2 | ||
| 3 | 3 | jQueryでは`$.fn`を拡張する事で、`$()`の返り値であるjQueryオブジェクトにメソッドを追加することが出来ます。 | |
| 4 | 4 | ||
@@ -15,6 +15,29 @@ jQueryでは`$.fn`を拡張する事で、`$()`の返り値であるjQueryオブ | |||
| 15 | 15 | ||
| 16 | 16 | ## どういう仕組み? | |
| 17 | 17 | ||
| 18 | + このjQueryプラグインがどのような仕組みで動いているのかを見てみましょう。 | ||
| 19 | + | ||
| 20 | + jQueryプラグインはprototype拡張のように `$.fn.greenify = function (){}` と拡張するルールでした。 | ||
| 21 | + | ||
| 22 | + `jQuery.fn`の実装を見てみると、実態は`jQuery.prototype`であるため実際にprototype拡張していることがわかります。 | ||
| 23 | + | ||
| 24 | + ``` | ||
| 25 | + // https://github.com/jquery/jquery/blob/2.1.4/src/core.js#L39 | ||
| 26 | + jQuery.fn = jQuery.prototype = { | ||
| 27 | + // prototypeの実装 | ||
| 28 | + } | ||
| 29 | + ``` | ||
| 30 | + | ||
| 31 | + | ||
| 32 | + `$()`は内部的に`new`をしてjQueryオブジェクトを返すので、このjQueryオブジェクトではprototypeに拡張したメソッドが利用できます。 | ||
| 33 | + | ||
| 34 | + ``` | ||
| 35 | + $(document.body); // 返り値はjQueryのインスタンス | ||
| 36 | + ``` | ||
| 37 | + | ||
| 38 | + | ||
| 39 | + つまり、jQueryプラグインはJavaScriptのprototypeをそのまま利用しているだけに過ぎないということがわかります。 | ||
| 40 | + | ||
| 18 | 41 | ## 実装してみよう | |
| 19 | 42 | ||
| 20 | 43 | `calculator`という拡張可能な計算機をjQuery Pluginと同じ方法で作ってみたいと思います。 | |
@@ -49,4 +72,6 @@ calculator.fn = calculator.prototype; | |||
| 49 | 72 | [import, calculator-example.js](../../src/jQuery/calculator-example.js) | |
| 50 | 73 | ||
| 51 | 74 | 実装をみてもらうと分かりますが、JavaScriptの`prototype`の仕組みをそのまま利用しています。 | |
| 52 | - そのため、特別な実装は必要なく「拡張する時は`calculator.prototype`の代わりに`calculator.fn`を拡張して下さい」というルールがあるだけとも言えます。 | ||
| 75 | + そのため、特別な実装は必要なく | ||
| 76 | + 「拡張する時は`calculator.prototype`の代わりに`calculator.fn`を拡張して下さい」 | ||
| 77 | + というルールがあるだけとも言えます。 | ||
| Back | FazBrowse Home | New Git URL |
0 commit comments