jQuery源码框架fn解读

时间:2022-04-02 09:43:49
(function( window, undefined ){
var jQuery = (function(){
var jQuery = function( selector, context ){
return new jQuery.fn.init( selector, context )
} jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context ){
if (!selector) return this;
var nodeList = (context || document).querySelectorAll( selector ),
i = 0,
length = nodeList.length;
for (; i<length; i+=1){
this[i] = nodeList[i];
}
this.length = nodeList.length;
return this;
}
}
//用fn的真正原因是
//如果不用fn,直接用jQuery.init 会返回undefined,主要是jQuery并不是new的对象,也就不能//访问原型,undefined不能设置原型
//jQuery.fn = {}可以直接访问init属性,所以fn必须写
console.log( jQuery.fn ); jQuery.fn.init.prototype = jQuery.fn; jQuery.fn.extend = jQuery.extend = function(obj){
var obj = obj || null;
if (!obj) return this;
for ( var i in obj){
if (!jQuery.fn[i]){
jQuery.fn[i] = obj[i];
}
}
return this;
} return jQuery;
})()
window.$ = window.jQuery = jQuery;
})( window, undefined )

下边是没有使用jQuery.fn的代码,使用了jQuery.fn的框架更简单,不用函数运行就可以对原型添加方法,也就是这一点,

因为直接jQuery.prototype不能直接添加方法,必须声明!但是jQuery.fn就可以,因为他不是原型而是一个{}object

jQuery.fn = jQuery.prototype = {};

<body>

    <h1>标题1</h1>
<h1>标题2</h1>
<h1>标题3</h1>
<script> var jQuery = function( selector, context ){
return new jQuery.prototype.init( selector, context );
} jQuery.prototype = { constructor: jQuery, init: function( selector, context ){ if ( !selector ) return;
var nodeList = ( context || document ).getElementsByTagName( selector ),
i = 0,
length = nodeList.length;
for (; i<length; i+=1){
this[i] = nodeList[i]
}
this.length = nodeList.length; return this
} } jQuery.prototype.init.prototype = jQuery.prototype;
jQuery.prototype.extend = function( obj ){
if ( !obj ) return;
for ( var i in obj ){
if ( !jQuery.prototype[i] ){
jQuery.prototype[i] = obj[i]
}
}
} jQuery.prototype.extend({
changeColor: function( color ){
if ( !color ) return;
var i = 0,
length = this.length;
for (; i<length; i+=1){
this[i].style.color = color;
}
return this;
}
});
jQuery('h1').changeColor('red');
//标准的写法 jQuery.fn.extend = jQuery.extend
//因为非标准的没有jQuery.fn 所以不能jQuery.extend()直接添加,必须jQuery.prototype.extend()
//进行添加,又因为jQuery.fn = jQuery.prototype = {},所以jQuery.fn是一个对象不用函数调用可以直//接添加
</script>
</body>