jQuery 如何允许其构造函数充当接受参数的函数,同时其构造函数还充当接受参数的函数?
我对 JavaScript 有点陌生,如果这是一个新手问题,请原谅(我已经查看了源代码,但很难尝试剖析)。
无论如何,举个例子$(document).ready(<args>);
两者都是构造函数$()
和原型(prototype)ready()
充当功能。如何?因为如果我尝试这样做:
var $ = function( selector ) {
if(selector == document) {
return document;
}
};
$.prototype = {
constructor: $,
ready: function( args ) {
if( isDomReady ) {
args.apply( document );
} else {
window.onload = args;
}
}
};
var isDomReady = ( document.addEventListener || document.readyState == ("complete"|"loaded"|true|4) || document.onreadystatechange() ) ? true : false;
$(document).ready(function() { alert("Wibbles!") });
我得到一个错误Uncaught TypeError: Object[object global] has no method 'ready'
最佳答案
你知道,这让我很感兴趣。您已经接受了一个答案,但如果它被证明有用,让我发布我的答案。有一个 fiddle created here
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
context: null,
isReady: null,
init: function( selector, context ) {
if (selector === document){
this.context = document;
this.selector = document;
}
console.log(this);
return this;
},
ready: function(func){
var args = Array.prototype.slice.call(this, arguments),
boundReadyFunc = func.bind(this, args.slice(1));
if (this.isReady){
func();
}
else {
document.addEventListener( "DOMContentLoaded", this.onReady.bind(this, func), false );
}
},
onReady: function(func){
console.log("onready");
this.isReady = true;
func.call(this);
},
};
jQuery.fn.init.prototype = jQuery.fn;
jQuery(document).ready(function(){
alert("Hey, here I am");
});
让我试着解释一下这是如何工作的。
每次您调用类似$(selector)
的方法时,都会创建一个新的 jQuery 实例,其中包含您提供的选项(请参阅return new jQuery.fn.init( selector,上下文 );
);
为了方便起见,我们将 jQuery 原型(prototype)公开为另一个全局名称 jQuery.fn
。为了使其真正可链接,init
函数必须返回一个新的 jQuery
实例。这就是为什么最后我们明确定义 jQuery
和 jQuery.init
的原型(prototype)是相同的。这样,您现在可以像这样链接函数调用
$(document).ready(DoSomethingHere)
希望这对您有所帮助。
另外,您可以在 github 上找到 jQuery 源代码.它是模块化的,很容易理解。
关于javascript - jQuery 原型(prototype)和构造函数链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15307243/