(function (root) {
var jQuery = function () {
return new jQuery.prototype.init();//如果写成new jQuery()会出现new (new jQuery())......无穷无尽的情形;因此采用new jQuery.prototype.init();并jQuery.fn.init.prototype = jQuery.fn=jQuery.prototype,实例化init也可以使用jQuery.prototype中的函数;
}
jQuery.prototype = jQuery.fn = {
init: function () {
}
}
jQuery.fn.extend = jQuery.extend = function () {
var target = arguments[0] || {}; //参数中的第一个
var length = arguments.length;
var deep = false;
var i = 0;
var option, name, copy, src, copyIsArray, clone;
//需要先判断typeof target =='boolean'是不是布尔值;
//再确定扩展的对象target,是arguments[0],arguments[1],还是jquery自身;
//i是被扩展的对象在arguments的数组下标;
if (typeof target == 'boolean') {
deep = target; //布尔值传给deep
target = arguments[1];
i = 2;
}
if (typeof target !== "object") { //目标不是对象;为空;
target = {};
}
if (length === 1) { //传入的值只有一个;
target = this; //给自身进行扩展;
i--;
}
for (; i < length; i++) {
if ((option = arguments[i]) !== null) { //不为null
for (name in option) {
copy = option[name]; //被复制的值;
src = target[name]; //扩展的值;
if (deep && (jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)))) {
//deep为深拷贝;拷贝的值是对象或者数组;
if (copyIsArray) { //如果是数组
copyIsArray = false; //方便下次使用
clone = src && jQuery.isArray(src) ? src : [];
} else { //否则是对象;
clone = src && jQuery.isPlainObject(src) ? src : {};
}
target[name] = jQuery.extend(deep, clone, copy);//递归,深拷贝;
} else if (copy != undefined) { //浅拷贝,或者被拷贝的值是基本数据类型;
target[name] = copy;
}
}
}
}
return target;
}
jQuery.fn.init.prototype = jQuery.fn
jQuery.extend({
//类型检测
isPlainObject: function (obj) {
return toString.call(obj) === "[object Object]";
},
isArray: function (obj) {
return toString.call(obj) === "[object Array]";
}
}); //先扩展类型检测的方法;
root.$ = root.jQuery = jQuery; //挂载到windows上;
})(window)