0

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

4

3 に答える 3

1

通常、関数内では、 this の値は関数が呼び出されるオブジェクトです:

var a = {
  b : { 
    c : function() {
      console.log(this);
    }
  }
};

a.b.c() // this will be a.b

var d = {};
d.e = a.b.c;

d.e() // this will be d

var f = a.b.c;

f() // this will be the global object (usually window) or undefined (strict mode)

明らかcallapply、それをオーバーライドして他のオブジェクトを関数に渡すことができます。もう 1 つ注目すべき例外がありますbind。Bind は、bind に渡されたオブジェクトで常に呼び出される新しい関数を作成します。を使用してこれを達成しますapply(おおよその実装については MDN を確認してください)。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

コードに適用:

$("#abc").myPlugin(); // check1 this is $("#abc")

$.myPlugin._attachMyPlugin(this, options); // check2 this is $.myPlugin (which is an instance of MyPlugin)
于 2013-11-14T15:13:53.513 に答える
0

$.myPlugin - MyPlugin クラスのインスタンス。メソッド _attachMyPlugin() は MyPlugin インスタンスに属します。このメソッドを呼び出すと、「this」は $.myplugin オブジェクトを指します。$.fn.someFunction を呼び出すと、"this" は jQuery オブジェクト $("#abc") を指します。

于 2013-11-14T15:08:27.283 に答える