Jac*_*ton 8 javascript jquery prototype object
jQuery如何允许其构造函数作为接受参数的函数,同时它的构造函数还充当接受参数的函数?
我对JavaScript有点新手,请原谅我这是否是一个noob问题,(我已经查看了源码,但很难尝试剖析).
无论如何,作为示例$(document).ready(<args>);构造函数$()和原型都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!") });
Run Code Online (Sandbox Code Playgroud)
我收到一个错误 Uncaught TypeError: Object[object global] has no method 'ready'
你知道,这引起了我的兴趣.你已经接受了一个答案,但是如果事实证明它有用的话,请让我发帖.这里有一个小提琴
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");
});
Run Code Online (Sandbox Code Playgroud)
让我试着解释一下这是如何工作的.
每次调用类似的东西时$(selector),都会创建一个新的jQuery实例,其中包含您提供的选项(请参阅参考资料return new jQuery.fn.init( selector, context ););
为方便起见,我们将jQuery原型公开为另一个全局命名的jQuery.fn.为了使其真正可链接,该init函数必须返回一个新jQuery实例.这就是为什么,最后,我们明确地定义了两者的原型jQuery并且jQuery.init是相同的.这样,您现在可以链接函数调用
$(document).ready(DoSomethingHere)
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
此外,您可以在github上找到jQuery源代码.它是模块化的,非常容易理解.
| 归档时间: |
|
| 查看次数: |
9758 次 |
| 最近记录: |