① js的全局代码区只有一个,这样就会造成同名变量的值会被覆盖
② 使用对象封装,将代码封装到对象中,但是如果对象被覆盖,则全部失效,风险极高
③ 使用工厂模式,将代码进行封装
④ 将封装的函数名去除,避免覆盖,但是函数没有办法被调用
⑤ 匿名自调用,可以在页面加载的时候调用一次,但是不能重复调用,并且数据没有办法获取
⑥ 使用闭包,将数据一次性挂载到window对象下
function jQuery(){var jquery = [dom1, dom2, dom3];jquery.fn1 = function(){…};jquery.fn2 = function(){…};return jquery;}
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 situationif ( typeof target === "boolean" ) {deep = target;// Skip the boolean and the targettarget = 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 passedif ( i === length ) {target = this;i--;}for ( ; i < length; i++ ) {// Only deal with non-null/undefined valuesif ( ( options = arguments[ i ] ) != null ) {// Extend the base objectfor ( name in options ) {copy = options[ name ];// Prevent Object.prototype pollution// Prevent never-ending loopif ( name === "__proto__" || target === copy ) {continue;}// Recurse if we're merging plain objects or arraysif ( deep && copy && ( jQuery.isPlainObject( copy ) ||( copyIsArray = Array.isArray( copy ) ) ) ) {src = target[ name ];// Ensure proper type for the source valueif ( copyIsArray && !Array.isArray( src ) ) {clone = [];} else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) {clone = {};} else {clone = src;}copyIsArray = false;// Never move original objects, clone themtarget[ name ] = jQuery.extend( deep, clone, copy );// Don't bring in undefined values} else if ( copy !== undefined ) {target[ name ] = copy;}}}}// Return the modified objectreturn target;
};
extend: JQ的继承方法, 为添加后续代码提供良好的扩展性,同时扩展插件也是从该继承该应地中扩展。
jQuery.extend({…}); 扩展一些工具方法(静态方法),如$.trim(), $.proxy()等。
jQuery.extend() 函数用于将一个或多个对象的内容合并到目标对象。
注意:
$.extend( target [, object1 ] [, objectN ] )
指示是否深度合并
$.extend( [deep ], target, object1 [, objectN ] )