jquery封装心得
- 具有独特的链式语法和短小清晰的多功能接口;
- 具有高效灵活的CSS选择器,并且可对CSS选择器进行扩展;
- 拥有便捷的插件扩展机制和丰富的插件
- jQuery兼容各种主流浏览器
jquery的封装原理
① js的全局代码区只有一个,这样就会造成同名变量的值会被覆盖
② 使用对象封装,将代码封装到对象中,但是如果对象被覆盖,则全部失效,风险极高
③ 使用工厂模式,将代码进行封装
④ 将封装的函数名去除,避免覆盖,但是函数没有办法被调用
⑤ 匿名自调用,可以在页面加载的时候调用一次,但是不能重复调用,并且数据没有办法获取
⑥ 使用闭包,将数据一次性挂载到window对象下
jQuery对象是一个以DOM为对象的特殊数组,并包含大量方法,简单可以理解为:
function jQuery(){
var jquery = [dom1, dom2, dom3];
jquery.fn1 = function(){…};
jquery.fn2 = function(){…};
return jquery;
}
jQuery.extend()源码示例
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[ 0 ] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// Skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !isFunction( target ) ) {
target = {};
}
// Extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( ( options = arguments[ i ] ) != null ) {
// Extend the base object
for ( name in options ) {
copy = options[ name ];
// Prevent Object.prototype pollution
// Prevent never-ending loop
if ( name === "__proto__" || target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
( copyIsArray = Array.isArray( copy ) ) ) ) {
src = target[ name ];
// Ensure proper type for the source value
if ( copyIsArray && !Array.isArray( src ) ) {
clone = [];
} else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) {
clone = {};
} else {
clone = src;
}
copyIsArray = false;
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend()方法
extend: JQ的继承方法, 为添加后续代码提供良好的扩展性,同时扩展插件也是从该继承该应地中扩展。
jQuery.extend({…}); 扩展一些工具方法(静态方法),如$.trim(), $.proxy()等。
<div id="log"></div>
<script>
$(function () {
var object1 = {
apple: 0,
banana: {weight: 52, price: 100},
cherry: 97
};
var object2 = {
banana: {price: 200},
durian: 100
};
/* object2 合并到 object1 中 */
$.extend(object1, object2);
var printObj = typeof JSON != "undefined" ? JSON.stringify : function(obj) {
var arr = [];
$.each(obj, function(key, val) {
var next = key + ": ";
next += $.isPlainObject(val) ? printObj(val) : val;
arr.push( next );
});
return "{ " + arr.join(", ") + " }";
};
$("#log").append( printObj(object1) );
})
</script>
jQuery.extend() 函数用于将一个或多个对象的内容合并到目标对象。
注意:
-
- 如果只为$.extend()指定了一个参数,则意味着参数target被省略。此时,target就是jQuery对象本身。通过这种方式,我们可以为全局对象jQuery添加新的函数。
-
- 如果多个对象具有相同的属性,则后者会覆盖前者的属性值。
$.extend( target [, object1 ] [, objectN ] )
指示是否深度合并
$.extend( [deep ], target, object1 [, objectN ] )