jQuery原型

时间:2012-11-07 00:03:26

标签: javascript jquery

根据此StackOverflow回答What does jQuery.fn mean?jQuery.fn.jquery中的fn属性是prototype属性的别名。我假设在完整代码低于

的这两种方法中这是相同的

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

我的问题是,例如,如果$ .fn.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));
    }
});

1 个答案:

答案 0 :(得分:10)

首先,原型只是对象。在这种情况下,是的:

jQuery.prototype === jQuery.fn

所以说jQuery.fn.map = function() {}就像说jQuery.prototype.map = function() {}

使用$(selector | dom node | ...) 实例化新的jquery对象时,您将返回一个jQuery对象,该对象会自动继承所有原型方法,包括地图,推文等。研究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 read the source并跟踪创建新对象时会发生什么。您可以在评论// Define a local copy of jQuery

下看到最接近顶部的内容
相关问题