gpt4 book ai didi

javascript - jQuery 原型(prototype)

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:08:55 25 4
gpt4 key购买 nike

根据这个 StackOverflow 答案 What does jQuery.fn mean? , jQuery.fn.jquery 中的 fn 属性是原型(prototype)属性的别名。我假设这在这两种方法中是相同的,其完整代码如下

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

那么我的问题是,例如,如果 $.fn.tweets 使用原型(prototype)来创建 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));
}
});

最佳答案

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

jQuery.prototype === jQuery.fn

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

当您使用 $(selector | dom node | ...)实例化一个新的 jquery 对象时,您将返回一个 jQuery 对象,它自动继承所有原型(prototype)方法,包括map、tweet等。研究Javascript的原型(prototype)继承模型以及对象原型(prototype)如何在new

方面工作

$ 只是对返回经过特殊修改的新对象jQuery 的引用。 $ 是一个返回新对象引用的函数。这是一个简化的例子(但是你真的应该更多地研究原型(prototype)继承,它已经被反复回答了很多次):

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

也可以随时read the source jQuery 并跟踪创建新对象时发生的情况。您可以在靠近顶部的注释 //Define a local copy of jQuery

下确切地看到发生了什么

关于javascript - jQuery 原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13261357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com