JQuery源码分析
测试环境
工具/版本说明 | 版本号 | 备注 |
---|
jQuery | 2.1.1 | |
sublime | 3 | |
1:源码结构之对象添加属性(后期持续更新中)
jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context );
}
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
}
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function( selector, context ) {
var match, elem;
if ( !selector ) {
return this;
}
if( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3){
match = [ null, selector, null ];
1:match = [ null, '<li>', null ];
2:match = [ null, '<li>1</li><li>2</li>', null ];
}else{
match = rquickExpr.exec( selector );
1:match=null;
2:match=['#div1',null,'div1'];
3:match=['<li>hello','<li>',null];
}
if( match && (match[1] || !context)){
if( match[1] ){
context = context instanceof jQuery ? context[0] : context;
jQuery.merge( this, jQuery.parseHTML() );
if(rsingleTag.test( match[1] ) && jQuery.isPlainObject( context )){
for ( match in context ) {
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
}else{
this.attr( match, context[ match ] );
}
}
}
}else{
}
}else{
}
return jQuery.makeArray( selector, this );
}
init.prototype = jQuery.fn;
源码分析
1.1constructor
function AAA(){}
//面向对象中两种写法是有区别的
AAA.prototype.name = "hello"
AAA.prototype.age = 30
AAA.prototype = {//覆盖原型;指向出现问题
name:"hello",
age:30
}
console.log(AAA.constructor)
console.log(AAA.prototype)
1.2属性操作原理浅要分析
<ul>
<li></li>
<li></li>
<li></li>
</ul>
$(function(){
console.log($('li').css('background','red'));
});
var aLi=document.getElementsByTagName('li');
for (var i =0; i < aLi.length; i++) {
aLi[i].style.background='red';
};
this = {
0='li',
1='li',
2='li',
length=3
};
for(var i=0;i<this.length;i++){
this[i].style.background='red';
}
1.3parseHTML解析
$(function(){
var str='<li>1</li><li>2</li><li>3</li><script>alert(4)<\/script>';
var arr=jQuery.parseHTML(str,document,true);
$.each(arr,function(i){
$('ul').append(arr[i]);
});
})
1.4merge
var arr1=['a','b'];
var arr1={
0:'a',
1:'b',
length:2
}
var arr2=['c','d'];
console.log($.merge(arr1, arr2))