3

根据这个 StackOverflow 答案jQuery.fn 是什么意思?,中的 fn 属性jQuery.fn.jquery是原型属性的别名。我认为这在这两种方法中是相同的,其完整代码如下

$.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 | ...)您将返回一个jQuery自动继承所有原型方法的对象,包括 map、tweet 等。研究 Javascript 的原型继承模型以及对象原型如何工作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 回答