JS数据类型磨练

我们晓得推断数据范例能够用typeof

定义一些数据

let num=1,str='str',bool=true,obj={},arr=[],sy=Symbol('s'),g,reg=/test/,date=new Date()

typeof运算符

typeof num //"number"
typeof str //"string"
typeof bool //"boolean"
typeof g //"undefined"
typeof obj //"object"
typeof arr //"object"
typeof reg//"object"
typeof date //"object"
typeof null //"object"

能够看出来typeof 对基础范例(除了null)能够推断出范例,然则对应对象,没有办法晓得详细的范例

instanceof 推断是不是为每一个范例的实例,经由过程这个要领能够推断出范例,我们对上述数据举行推断

function Person(){}
let p=new Person()
function Foo(){}
let f=new Foo()
num instanceof Number //false 
str instanceof String //false
arr instanceof Object //true
arr instanceof Array //true 
obj instanceof Object //true 
obj instanceof Array //false 
reg instanceof RegExp //true
date instanceof Date //true

constructor

arr.constructor ===Array //true 
obj.constructor ===Object //true 
str.constructor === String  //true

从输出的效果我们能够看出,除了undefined和null,其他范例的变量均能运用constructor推断出范例。
不过运用constructor也不是保险的,由于constructor属性是能够被修正的,会致使检测出的效果不正确

Object.prototype.toString.call

Object.prototype.toString.call(str) //"[object String]"

Object.prototype.toString.call(obj) //"[object Object]"

Object.prototype.toString.call(null) //"[object Null]"

Object.prototype.toString.call(num) ///"[object Number]"

...

每一个对象都有一个toString()要领,当该对象被示意为一个文本值时,或许一个对象以预期的字符串体式格局引用时自动挪用。默许情况下,toString()要领被每一个Object对象继续。假如此要领在自定义对象中未被掩盖,toString() 返回 “[object type]”,个中type是对象的范例

那为何Object.toString.call(params) 会报错呢?

Object.toString.call(num)

Uncaught TypeError: Function.prototype.toString requires that 'this' be a Function at Number.toString (<anonymous>) at <anonymous>:1:17

这是为何呢,由于Object为组织函数,Object组织函数自身没有toString要领。
遵照原型链关联,Object组织函数的上游原型链是Function.prototype。
所以,你挪用Object.toString.call(param)本质上是挪用Function.prototype.toString.call(param),这里须要的参数范例是函数,所以会报错。

    原文作者:canoe
    原文地址: https://segmentfault.com/a/1190000018659618
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞