jqueryプラグインの作り方を勉強中です。
これが私のコードです:
<!DOCTYPE html>
<html>
<head>
<title>JS Study</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
(function($, undefined) {
function MyPlugin() {
this.myoption = "myvalue";
}
$.extend(MyPlugin.prototype, {
_attachMyPlugin: function(target, settings) {
console.log(this); // check2
}
});
$.fn.myPlugin = function(options) {
console.log(this); // check1
$.myPlugin._attachMyPlugin(this, options);
return this;
};
$.myPlugin = new MyPlugin(); // singleton instance
}(jQuery));
$(document).ready(function(){
$("#abc").myPlugin();
});
</script>
<h1 id="abc">title1</h1>
</body>
</html>
this
_attachMyPlugin() を呼び出すと値が変わる理由がわかりません。check1 ではthis
、jQuery オブジェクトのみを参照しているようです。それは私には奇妙に思えません。ただし、check2 で「this」は MyPlugin オブジェクトを参照しているようです。なんで?
this
キーワードの参照オブジェクトは、new
演算子または呼び出し.apply()
/.call()
関数なしで変更できますか? もしそうなら、なぜですか?
これが Chrome コンソールの結果です。
[h1#abc、コンテキスト: ドキュメント、セレクター: "#abc"、jquery: "1.9.1"、コンストラクター: 関数、init: 関数…] w.html:21 MyPlugin {myoption: "myvalue", _attachMyPlugin: 関数} w.html:16