类型系统
javascript 类型系统可以分为标准类型和对象类型,进一步标准类型又可以分为原始类型和引用类型,而对象类型又可以分为内置对象类型、普通对象类型、自定义对象类型。
类型转化表
类型判断
typeof
instanceof
Object.prototype.toString
constructor
typeof
可以识别标准类型(null
除外)
不可识别具体的对象类型(Function
除外)
1 2 3 4 5 6 7 8 9 10 11 typeof 1 ; typeof '' ; typeof undefined ; typeof true ; typeof null ; typeof []; typeof {}; typeof function ( ) {};
instanceof
instanceof
左侧为查询变量,右侧为标识对象的类
能够判别内置对象类型
不能判别原始类型
能够判别自定义类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 [] instanceof Array ; /\d/ instanceof RegExp ; 1 instanceof Number ; 'xiaohong' instanceof String ; function Point (x, y ) { this .x = x; this .y = y; } var c = new Point(2 , 3 );c instanceof Point;
实现一个 instanceof 1 2 3 4 5 6 7 8 9 function instanceOf (left, right ) { let proto = left.__proto__; let prototype = right.prototype; while (true ) { if (proto === null ) return false ; if (proto === prototype) return true ; proto = proto.__proto__; } }
Object.prototype.toString.call()
可以识别标准类型,及内置对象类型
不能识别自定义类型
1 2 3 4 5 6 7 8 9 10 11 12 13 Object .prototype.toString.call(21 ); Object .prototype.toString.call([]); Object .prototype.toString.call(/[A-Z]/ ); function Point (x, y ) { this .x = x; this .y = y; } var c = new Point(2 , 3 ); Object .prototype.toString.call(c);
为了方便使用,使用函数封装如下:
1 2 3 4 5 6 function typeProto (obj ) { return Object .prototype.toString.call(obj).slice(8 , -1 ); } typeProto('guo' ); typeProto({});
constructor
constructor 指向构造这个对象的构造函数本身..
可识别原始类型
可识别内置对象类型
可识别自定义类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 'guo' .constructor === String ; (1 ).constructor === Number ; true .constructor === Boolean ; ({}.constructor === Object ); new Date ().constructor === Date ; [].constructor === Array ; function People (x, y ) { this .x = x; this .y = y; } var c = new People(2 , 3 );c.constructor === People;
为了方便使用,使用函数封装如下:
1 2 3 4 5 6 7 function getConstructorName (obj ) { return obj && obj.constructor && obj.constructor.toString().match(/function\s*([^(]*)/ )[1 ]; } getConstructorName(new Date ()); getConstructorName(null ); getConstructorName(12 );
类型判断对比表 其中红色的单元格表示该判断方式不支持的类型。