typeof
- 数组、null不能正确判断,会被判断为object,其他都可正确判断
typeof(2) ----- number
typeof('hello') ----- string
typeof(true) ----- boolean
typeof(undefined) ----- undefined
typeof([]) ----- object
typeof(null) ----- object
typeof({}) ----- object
typeof(function()) ----- function
instanceof
- 只能正确判断引用类型数据,不能正确判断基础数据类型
- 内部运行机制是判断在其原型链中是否能找到该类型的原型
- null和undefined不能被判断,因为它不能被转成实例
2 instanceof Number ------ false
'hello' instanceof String ------ false
true instanceof Boolean ------ false
let obj = {a:1};obj instanceof Object ------- true
let fn = function(){}; fn instanceof Function ------- true
[] instanceof Array ------- true
- instanceof的原理和内部实现
instanceof运算符用于检测构造函数的prototype属性是否存在于某个对象的原型链上- 其中
object是要检测的对象,constructor是构造函数。如果对象是构造函数的实例,或者对象的原型链上存在构造函数的prototype属性,则表达式返回true;否则返回false
function myInstanceof(left,right){
//获取检测对象的原型
let proto = left.getPrototypeOf(left)
//获取构造函数的prototype对象
let prototype = right.prototype
while(true) {
//判断构造函数的prototype对象是否在对象的原型链上
if(!proto) return false
if(proto === prototype) return true
//如果没有找到,就从对象的原型链上继续寻找
proto = Object.getPrototypeOf(proto)
}
}
constructor
- 一是判断数据的类型,二是对象实例通过 constrcutor 对象访问它的构造函数
- 如果创建一个对象 来改变它的原型,constructor 就不能用来判断数据类型了
- null和undefined不能被判断,因为没有对应的包装类,不存在constructor
2.constructor === Number ----- true
'hello'.constructor === String ----- true
true.constructor === Boolean ----- true
([]).constructor === Array ----- true
(function fn() {}).constructor === Function ----- true
({}).constructor === Object ----- true
Object.prototype.toString.call()
- Object.prototype.toString.call() 使用 Object对象的原型方法toString来判断数据类型
- toString是Object的原型方法,而 Array、function 等类型作为 Object 的实例,都重写了toString 方法,不同的对象类型调 用 toString 方法时,根据原型链的知识,调用的是对应的重写之后的toString 方法(function 类型返回内容为函数体的字符串,Array 类型返回元素组成的字符串…),而不会去调用 Object 上原型 toString 方法(返回对象的具体类型),所以采用 obj.toString() 不能得到其对象类型,只能将 obj 转换为字符串类型;因此,在想要 得到对象的具体类型时,应该调用 Object 原型上的 toString 方法
Object.prototype.toString.call(2) ----- [object Number]
Object.prototype.toString.call("hello") ----- [object String]
Object.prototype.toString.call(true) ----- [object Boolean]
Object.prototype.toString.call([]) ----- [object Array]
Object.prototype.toString.call(function fn() {}) ----- [object Function]
Object.prototype.toString.call(undefined) ----- [object Undefined]
Object.prototype.toString.call(null) ----- [object Null]
----------------------------------------------------------------------------------------每日一题:2024/4.23