3

この StackOverflow の回答によると、jQuery.fn の意味は何ですか? の fn プロパティjQuery.fn.jqueryは、prototype プロパティのエイリアスです。これは、完全なコードが以下にあるこれら2つのメソッドで同じであると思います

$.fn.map = function()$.fn.tweets = function()

私の質問は、たとえば、 $.fn.tweets がプロトタイプを使用して tweets メソッドを作成する場合、このコードはそれを$('tweets').tweets 呼び出すでしょうか...

var $tweets = $('#tweets').tweets({
        query: buildQuery(approxLocation),
        template: '#tweet-template'
    });

もしそうなら、どのようにそのメソッドをトリガーすることができますか. たとえば、ファイルの読み込み時に変数を作成するだけで、クエリなどの他のメソッドが内部にある関数がトリガーされますか? ご協力いただきありがとうございます

メソッドの完全なコード

  $.fn.map = function(method) {
         console.trace();
         console.log(method);
        if (method == 'getInstance') {
            console.log("fn.map");
            return this.data('map');
        }

        return this.each(function() {
            var $this = $(this);
            var map = $this.data('map');

            if (map && MyMap.prototype[method]) {
                 map[method] (Array.prototype.slice.call( arguments, 1 ));
            } else if ( typeof method === 'object' || ! method ) {
                var options = method;
                $this.data('map', new MyMap( this, options ));
            } else {
                $.error( 'Method ' +  method + ' does not exist on jQuery.map' );
            }
        });
    }

   $.fn.tweets = function(method) {

        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {

            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.tweets' );
        }
    }

それらのメソッドを呼び出す変数?

 var $tweets = $('#tweets').tweets({
        query: buildQuery(approxLocation),
        template: '#tweet-template'
    });
var $map = $('#map').map({
    initialLocation: approxLocation,
    radius: 1000,
    locationChanged: function(location) {
        $tweets.tweets('setQuery', buildQuery(location));
    }
});
4

1 に答える 1

10

まず、プロトタイプは単なるオブジェクトです。この場合、はい:

jQuery.prototype === jQuery.fn

だから言うことjQuery.fn.map = function() {}は言うようなものですjQuery.prototype.map = function() {}

新しいjqueryオブジェクトをインスタンス化すると、マップ、ツイートなどを含むすべてのプロトタイプメソッドを自動的に継承$(selector | dom node | ...)するオブジェクトが返されます.JavascriptjQueryのプロトタイプ継承モデルと、オブジェクトプロトタイプがどのように機能するかを調べてください。new

$は、特別に変更された新しいオブジェクトjQueryを返す単なる参照です。新しいオブジェクト参照を返す関数です。簡単な例を次に示します (ただし、プロトタイプの継承についてはもっと調べておく必要があります。何度も繰り返し回答されています)。$

var A = function() {
};

A.prototype.doThing = function() {
};

var newObj = new A();

newObj.doThing // this new object has this method because it's on A's prototype

そうnewObj.doThingです$(selector).tweet

また、jQuery のソースを自由に読んで、新しいオブジェクトが作成されたときに何が起こるかを追跡してください。コメントの下で何が起こっているかを正確に確認できます// Define a local copy of jQuery

于 2012-11-07T00:14:45.767 に答える