@Lxyour
2018-09-14T13:54:23.000000Z
字数 1422
阅读 1004
JavaScript
typeof用于检测基本类型,不适合Array、NaN、null
typeof 100 //"number"typeof true //"boolean"typeof function //"function"typeof(undefined) //"undefined"typeof new Object() //"object"typeof [0, 2] //"object"typeof NaN //"number"typeof null //"object"
typeof null === "object" ?
对于对象类型我们用instanceof更适合。
obj instanceof Object
[1, 2] instanceof Array === truenew Object() instanceof Array === false
toString 是 Object 原型对象上的方法,使用 call 来调用该方法会返回调用者的类型字符串,格式为 [object,xxx],xxx 是调用者的数据类型,包括:String、Number、Boolean、Undefined、Null、Function、Date、Array、RegExp、Error、HTMLDocument 等, 基本上,所有的数据类型都可以通过这个方法获取到。
Object.prototype.toString.call([]) === "[object Array]";Object.prototype.toString.call(function () {}) === "[object Function]";Object.prototype.toString.call(null) === "[object Null]";Object.prototype.toString.call(undefined) === "[object Undefined]";Object.prototype.toString.call(null) === "[object Object]"; //IE6/7/8
当一个函数 F被定义时,JS引擎会为F添加 prototype 原型,然后再在 prototype上添加一个 constructor 属性,并让其指向 F 的引用。如下所示:
function F() {}F.prototype
当执行 var f = new F() 时,F 被当成了构造函数,f 是F的实例对象,此时 F 原型上的 constructor 传递到了 f 上,因此 f.constructor === F;
可以看出,F 利用原型对象上的 constructor 引用了自身,当 F 作为构造函数来创建对象时,原型上的 constructor 就被遗传到了新创建的对象上, 从原型链角度讲,构造函数 F 就是新对象的类型。这样做的意义是,让新对象在诞生以后,就具有可追溯的数据类型。
同样,JavaScript 中的内置对象在内部构建时也是这样做的:
[].constructor === Array // true''.constructor === String // true
根据数据类型的特征来判断,比如可以检测是否有push()方法来判定Array;