typeof
一般用于判断基本数据类型
⚠️ 当判断null时返回’object’
⚠️ 当判断引用类型时 如果是函数会返回’function’ 其他都都是返回’object’
1 2 3 4 5 6 7 8
| console.log(typeof 1) console.log(typeof '1') console.log(typeof true) console.log(typeof null) console.log(typeof undefined) console.log(typeof function () {}) console.log(typeof []) console.log(typeof {})
|
instanceof
用来判断引用类型,原理是检测构造函数的prototype是否在某个实例对象的原型链上
⚠️ 如果判断基础数据类型都返回false
1 2 3 4 5 6 7 8 9
| object instanceof constructor
console.log(6 instanceof Number); console.log(true instanceof Boolean); console.log('nanjiu' instanceof String); console.log([] instanceof Array); console.log(function(){} instanceof Function); console.log({} instanceof Object);
|
⚠️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.prototype.toString.call(1) ; Object.prototype.toString.call(true) ; Object.prototype.toString.call(Symbol()); Object.prototype.toString.call(undefined) ; Object.prototype.toString.call(null) ; Object.prototype.toString.call(new Function()) ; Object.prototype.toString.call(new Date()) ; Object.prototype.toString.call([]) ; Object.prototype.toString.call(new RegExp()) ; Object.prototype.toString.call(new Error()) ; Object.prototype.toString.call(document) ; Object.prototype.toString.call(window) ;
|
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 new Number(1).constructor === Number new Function().constructor === Function true.constructor === Boolean ''.constructor === String new Date().constructor === Date [].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
console.log(f.constructor)
|
https://zhuanlan.zhihu.com/p/453520879