/* 给JQuery原型添加属性和方法 */ jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, //版本 constructor: jQuery, //添上constructor 指向构造函数,修复constructor init: function(selector, context, rootjQuery) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if (!selector) { return this; } // Handle HTML strings if (typeof selector === 'string') { if ( selector.charAt(0) === '<' && selector.charAt(selector.length - 1) === '>' && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [null, selector, null]; } else { match = rquickExpr.exec(selector); }
由这段代码可知,jQuery.fn就是jQuery.prototype,现在要把jQuery的原型重写,重写一定会破坏constructor指向jQuery的这个构造函数,所以要手动添加;小写的jquery是版本号
var jq = new Jquery() console.log(jq.jquery) // 2.0.3
接下来是重点的init,没错就是那个不像构造函数的init
init: function(selector, context, rootjQuery) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if (!selector) { return this; }
selector参数是选择器字符串,其他两个参数暂且不论,然后定义了match,elem;紧接着来了一个if语句,if(!selector)的意思就是selector为“”,null,undefined,false对应的情况注释给我们了HANDLE: $(""), $(null), $(undefined), $(false) 处理四种获取不到的情况,jQuery里面直接去return this;不但终止了下列代码的执行,还返回了this,这个this就是jQuery.prototype
// Handle HTML strings if (typeof selector === 'string') { if ( selector.charAt(0) === '<' && /* chatAt(下标)截取对应下标字符的意思 selector.charAt(selector.length - 1) === '>' && * 这3句判断了selector字符串是不是长<a>或<aaa>的总之要有一个尖括号,而且尖括号里面必须有字符 selector.length >= 3 */ 这句话并不能保证像<1>这种的 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [null, selector, null]; } else { match = rquickExpr.exec(selector); }
这一段是如果$()括号里面不是上述四种的情况,那么就是一个有值的字符串。再进入一个if...else if语句(这里截取的是if里面嵌套的if else语句),如果selector是一个字符串类型,那么就可以再判断他是不是一个标签类似于'<aaa>',如果类似这种就把[null,selector,null]这样一个数组赋值给前面定义的match,否则,像'a<aa>'或'<br />r'这种不符合以尖括号开头和结尾的字符串,match就会等于rquickExpr.exec(selector);
那么这是什么意思呢?正则的exec()方法返回的是一个数组,那么这个数组长什么样呢?上面已经定了rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,这就涉及到正则,简单的说下: