JS框架设计读书笔记之-核心模块

随笔记录一下读书心得

1. 框架模块-核心模块

  该模块是框架最先执行的部分,jQuery与vue中都有初始化的代码。

  模块的功能主要是:对象扩展、数组化、类型判定、事件绑定和解绑、无冲突处理、模块加载、domReady

  之前阅读过jQuey的部分源码,对这些功能还是有感触的,比如说:

  对象扩展:

jQuery.extend({
merge: function(first, second) {
var len = +second.length,
j = 0,
i = first.length; for (; j < len; j++) {
first[i++] = second[j];
} first.length = i; return first;
},
grep: function(elems, callback, invert) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
for (; i < length; i++) {
callbackInverse = !callback(elems[i], i);
if (callbackInverse !== callbackExpect) {
matches.push(elems[i]);
}
} return matches;
},
map: function(elems, callback, arg) {
var length, value,
i = 0,
ret = [];
if (isArrayLike(elems)) {
length = elems.length;
for (; i < length; i++) {
value = callback(elems[i], i, arg); if (value != null) {
ret.push(value);
}
}
} else {
for (i in elems) {
value = callback(elems[i], i, arg); if (value != null) {
ret.push(value);
}
}
}
return concat.apply([], ret);
},
guid: 1,
proxy: function(fn, context) {
var tmp, args, proxy; if (typeof context === "string") {
tmp = fn[context];
context = fn;
fn = tmp;
}
if (!jQuery.isFunction(fn)) {
return undefined;
}
args = slice.call(arguments, 2);
proxy = function() {
return fn.apply(context || this, args.concat(slice.call(arguments)));
};
proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy;
}
})

  数组化:

jQuery.fn = jQuery.prototype = {
toArray: function() {
return slice.call(this);
},
makeArray: function(arr, results) {    
var ret = results || []; if (arr != null) {
if (isArrayLike(Object(arr))) {
jQuery.merge(ret,
typeof arr === "string" ? [arr] : arr
);
} else {
push.call(ret, arr);
}
}
return ret;
}
}

  类型判断:isFunction、type、isArrayLike

jQuery.extend({
noop: function() {},
isFunction: function(obj) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
isWindow: function(obj) {
return obj != null && obj === obj.window;
}, isNumeric: function(obj) {
var type = jQuery.type(obj);
return (type === "number" || type === "string") &&
// subtraction forces infinities to NaN
!isNaN(obj - parseFloat(obj));
}, isPlainObject: function(obj) {
var proto, Ctor;
if (!obj || toString.call(obj) !== "[object Object]") {
return false;
}
proto = getProto(obj);
if (!proto) {
return true;
}
Ctor = hasOwn.call(proto, "constructor") && proto.constructor;
return typeof Ctor === "function" && fnToString.call(Ctor) === ObjectFunctionString;
}, isEmptyObject: function(obj) {
var name;
for (name in obj) {
return false;
}
return true;
}
})

  事件绑定和解绑:on?

  无冲突处理:noConflict

// $可能为其他框架的符号
var _jQuery = window.jQuery, _$ = window.$;
jQuery.exteng({
noConflict: function(deep){
// 如果冲突 就把jQuery还回去
window.$ = _$;
if(deep){
window.jQuery = _jQuery;
}
return jQuery;
}
})

  模块加载:初始化?

  domReady:利用DOMContentLoaded   这个接口属于Event 用法如下(来自MDN):

document.addEventListener("DOMContentLoaded",callback)

  第一节先这么写着,后面写一些比较有意思的函数

上一篇:django 初始命令


下一篇:js函数常见的写法以及调用方法