jQuery原型

3
根据这个StackOverflow答案 (什么是jQuery.fn?),在jQuery.fn.jquery中的fn属性是prototype属性的别名。我假设在下面这两个方法中也是一样的,它们的完整代码如下: $.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));
    }
});
1个回答

10

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

jQuery.prototype === jQuery.fn
jQuery.fn.map = function() {} 就像说 jQuery.prototype.map = function() {} 当你使用 $(selector | dom node | ...) 实例化一个新的 jQuery 对象时,你会返回一个自动继承所有原型方法(包括 map、tweet 等)的 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源代码并跟踪创建新对象时发生的情况。您可以在顶部附近看到确切的操作,在注释//定义jQuery的本地副本下方。


谢谢,那么在文件加载时创建这个变量会触发原型方法吗?在我提供的代码中,它没有使用'new'构造函数。var $tweets = $('#tweets').tweets({ - BrainLikeADullPencil
@user1647484пәљз„¶иЂЊпәЊењЁ$е‡Ңж•°е†…йѓЁпәЊйЂљиү‡newе€›е»ғдғ†е®һй™…зљ„jQueryжһ„йЂ е‡Ңж•°е®һдң‹е№¶иү”е›һгЂ‚иҮ·жџӨзњ‹ж­¤з­”жҰ€д»Өдғ†и§Әе…¶е†…йѓЁжњғ制。 - Bergi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接