js是弱类型的语言,所以在声明变量时无需设定类型.但这也会产生一些问题,所以js变量类型的检测很有必要.
通用的类型检测方法
1. 通用检测方法1
Function.prototype.call.bind(Object.prototype.toString);
2. 通过检测方法2
Object.prototype.toString.call(obj)
3. 以上两种方法的区别:
第一种方法是许多框架所采用的方法,采用的原因主要是可以防止原型污染.采用第二种方式时,若自己在代码中重写了Object.prototype.toString方法,将得不到正确的结果,但是第一种写法仍然可以。
typeof类型检测
typeof能够检测出基本数据类型,比如number, undefined, string, boolean, function, 但是typeof null 和 typeof {},以及 typeof []都是object.所以需要检测某个非object类型的变量可以使用typeof.
instanceof类型检测
a instanceof A 检测a是否是A的实例,是返回 true,不是返回false;
[] instanceof Object ===> true; [] instanceof Array ===> true;
1 instanceof Number ===> false; new Number(1) instanceof Number ===> true;
'1' instanceof String ===> false; new String('1') instanceof String ===> true;
false instanceof Boolean ===> false; new Boolean(false) instanceof Boolean ===> ture;
### 通过上面的例子可以分析: 通过new得到的实例一定是该类型的实例(感觉像废话,不过确实是这样的);所以通过instanceof去判断变量类型有局限性.