01闭包
underscore写法
(function(){
...
}.call(this));
jQuery写法
(function(window, undefined) {
...
})(window);
02原型赋值
便于压缩
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
压缩后,ArrayProto可能变成a
a.xxx = ...
03数据判断
判断是否为dom,dom的nodeType属性值为1.这里用!!!强转为boolean值
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
判断是否为数组,用call函数改变作用域避免obj没有toString函数报错
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
判断是否为对象,先用typeof判断数据类型。函数属于对象,再使用!!obj来区分null
_.isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
判断是否为arguments,利用arguments特有属性callee
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return _.has(obj, 'callee');
};
}
判断是否是NaN
_.isNaN = function(obj) {
return _.isNumber(obj) && obj !== +obj;
};
判断是否是Boolean,true/false/new Boolean()
.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};
判断是否是undefined 小技巧: 用void 0来表示undefined
_.isUndefined = function(obj) {
return obj === void 0;
};