5-5Underscore01

xiaoxiao2021-02-28  82

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) { // 1.它是一个数 // 2.不等于自己 // +放在变量前面的作用是把后面的变量变成一个数 // 这里仍加上+是为了把var num = new Number()这种没有值的数字也归为NaN。 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; };
转载请注明原文地址: https://www.6miu.com/read-44625.html

最新回复(0)