5-5Underscore01

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;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值