《编写可维护的JavaScript》 笔记

时间:2024-01-20 17:22:23

《编写可维护的JavaScript》 笔记

我的github iSAM2016

概述

本书的一开始介绍了大量的编码规范,并且给出了最佳和错误的范例,大部分在网上的编码规范看过,就不在赘述
重点是总结了数据类型的判断,我再此和underscore中的类型判断一起做个总结:

总结

  1. string number undefined boolean

    • 这四中数据类型使用typeof 在检测即可

      typeof '1' == 'string'

      typeof 1 == 'number'

      typeof found == 'boolean' && found

      typeof undefined == 'undefined'
  2. null

    • 使用 value === null
  3. 引用类型

    1. 一般

      • 使用instanceof
    2. array

      • Array.prototype.toString.call(array) == '[object Array]'
  4. function

    * typeof fn === 'function'

underscore 的实现

基本类型的判断
undersocre 中的基本类型有的判断使用的是
```
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
_.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) === '[object ' + name + ']';
};
});


// null的类型有些特殊,typeof null == 'object' null == undefined ,检测他就和null自身比较,null用处多是初始化变量,这个变量可能是个对象在没有给变量赋值的时候,理解null可以是对象的占位符 可以var value = null;

_.isNull = function(obj) {

return obj === null;

};


// 看到源码可以知道,函数也被视为对象,undefined,null,NaN等则不被认为是对象

_.isObject = function(obj) {

var type = typeof obj;

return type === 'function' || type === 'object' && !!obj;

};


 if (typeof /./ != 'function' && typeof Int8Array != 'object') {
_.isFunction = function(obj) {
return typeof obj == 'function' || false;
};

}


_.isBoolean = function(obj) {

return obj === true || obj === false || toString.call(obj) === '[object Boolean]';

};


// 对于Arguments判断,IE9以前的版本,Object.prototype.toString返回的会是'[object Object]'而不是'[object Arguments],需要通过判断对象是否具有callee来确定其是否Arguments类型,underscore对此进行了修正:

if (!_.isArguments(arguments)) {

_.isArguments = function(obj) {

return _.has(obj, 'callee');

};

}



// 使用void 0 原因是undefined 可以被重写

_.isUndefined = function(obj) {

return obj === void 0;

};