类型判断

Martin

typeof

一般用于判断基本数据类型

⚠️ 当判断null时返回’object’

⚠️ 当判断引用类型时 如果是函数会返回’function’ 其他都都是返回’object’

1
2
3
4
5
6
7
8
console.log(typeof 1) // number
console.log(typeof '1') // string
console.log(typeof true) // boolean
console.log(typeof null) // object
console.log(typeof undefined) // undefined
console.log(typeof function () {})// function
console.log(typeof []) // object
console.log(typeof {}) // object

instanceof

用来判断引用类型,原理是检测构造函数的prototype是否在某个实例对象的原型链上

⚠️ 如果判断基础数据类型都返回false

1
2
3
4
5
6
7
8
9
object instanceof constructor


console.log(6 instanceof Number); // false
console.log(true instanceof Boolean); // false
console.log('nanjiu' instanceof String); // false
console.log([] instanceof Array); // true
console.log(function(){} instanceof Function); // true
console.log({} instanceof Object); // true

⚠️null和undefined是无效的对象,所以他们不会有constructor属性

Object.prototype.toString.call()

toString() 是 Object 的原型方法,调用该方法,默认返回当前对象的 [[Class]] 。这是一个内部属性,其格式为 [object Xxx] ,其中 Xxx 就是对象的类型。

对于 Object 对象,直接调用 toString() 就能返回 [object Object] 。而对于其他对象,则需要通过 call / apply 来调用才能返回正确的类型信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
Object.prototype.toString.call('') ;   // [object String]
Object.prototype.toString.call(1) ; // [object Number]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(Symbol()); //[object Symbol]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]
Object.prototype.toString.call(new Function()) ; // [object Function]
Object.prototype.toString.call(new Date()) ; // [object Date]
Object.prototype.toString.call([]) ; // [object Array]
Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
Object.prototype.toString.call(new Error()) ; // [object Error]
Object.prototype.toString.call(document) ; // [object HTMLDocument]
Object.prototype.toString.call(window) ; //[object global] window 是全局对象 global 的引用

constructor(构造函数)

函数在被定义时JS引擎会自动给函数加上一个prototype属性,属性上有constructor并指向该函数
当执行let f = new F()时,F被当成了构造函数,f是F的实例对象,此时F原型上的constructor属性传递到了f上,所以f.constructor===F

1
2
3
4
5
6
7
8
9
10
function F(){}
let f = new F()

f.constructor === F // true
new Number(1).constructor === Number //true
new Function().constructor === Function // true
true.constructor === Boolean //true
''.constructor === String // true
new Date().constructor === Date // true
[].constructor === Array

⚠️****注意:

  • null和undefined是无效的对象,所以他们不会有constructor属性
  • 函数的construct是不稳定的,主要是因为开发者可以重写prototype,原有的construction引用会丢失,constructor会默认为Object
1
2
3
4
5
6
7
function F(){}
F.prototype = {}

let f = new F()
f.constructor === F // false

console.log(f.constructor) //function Object(){..}

https://zhuanlan.zhihu.com/p/453520879