根据这个StackOverflow的答案,jQuery.fn是什么意思?,fn属性in jQuery.fn.jquery是prototype属性的别名.我假设在完整代码如下的这两种方法中这是相同的
$.fn.map = function() 和 $.fn.tweets = function()
我的问题是,例如,如果$ .fn.tweets使用原型来创建推文方法,那么这段代码是否$('tweets').tweets 会调用它...
var $tweets = $('#tweets').tweets({
query: buildQuery(approxLocation),
template: '#tweet-template'
});
Run Code Online (Sandbox Code Playgroud)
如果是这样,它将如何触发该方法.例如,仅仅在文件加载上创建变量是否会触发该函数,其中包含其他方法,即查询?谢谢你的帮助
完整的方法代码
$.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' );
}
}
Run Code Online (Sandbox Code Playgroud)
调用这些方法的变量?
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));
}
});
Run Code Online (Sandbox Code Playgroud)
And*_*Ray 10
首先,原型只是对象.在这种情况下,是的:
jQuery.prototype === jQuery.fn
Run Code Online (Sandbox Code Playgroud)
所以说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
Run Code Online (Sandbox Code Playgroud)
所以newObj.doThing就像$(selector).tweet
也可以随意阅读 jQuery 的源代码并跟踪创建新对象时发生的情况.您可以在评论中看到正好发生的事情// Define a local copy of jQuery