instanceof与typeof详解

本文详细解析了JavaScript中instanceof与typeof操作符的区别。typeof用于判断变量的数据类型,如number、string等;instanceof则用于判断对象是否为特定类的实例。文章通过实例展示了两种操作符的使用场景,并深入探讨了instanceof在特殊情况下如何工作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

instanceof与typeof的区别

typeof 判断 值得类型
instanceof 判断 是否是某一对象的实例

console.log(typeof 11) // number
console.log( {} instanceof Object ) // true  
typeof有哪些值
  • string
  • number
  • object
  • undefined
  • symbol
  • function
  • boolean
// string
console.log( typeof '一一' === string ) // true

// number
console.log( typeof 11 === number ) // true

// function
console.log( typeof (()=>{}) === function ) // true

// undefined
console.log( typeof undefined === undefined ) // true

// symbol
console.log( typeof Symbol() === symbol ) // true

// boolean
console.log( typeof true === boolean ) // true

// object
console.log( typeof null === object ) // true
console.log( typeof {} === object ) // true
console.log( typeof [] === object ) // true
instanceof的一些特殊情况
  • 直接创建字符串时,检查原型会找到undefined
  • 创建非Object实例的对象的方法时,会返回false
  • 只要在原型中能查找到对应构造函数,都会返回true
var simpleStr = "This is a simple string"; 
var myString  = new String();
var newStr    = new String("String created with constructor");
var myDate    = new Date();
var myObj     = {};
var myNonObj  = Object.create(null);

simpleStr instanceof String; // 返回 false, 检查原型链会找到 undefined
myString  instanceof String; // 返回 true
newStr    instanceof String; // 返回 true
myString  instanceof Object; // 返回 true

myObj instanceof Object;    // 返回 true, 尽管原型没有定义
({})  instanceof Object;    // 返回 true, 同上
myNonObj instanceof Object; // 返回 false, 一种创建非 Object 实例的对象的方法

myString instanceof Date; //返回 false

myDate instanceof Date;     // 返回 true
myDate instanceof Object;   // 返回 true
myDate instanceof String;   // 返回 false
instanceof的实现

要了解实现,我们先看看instanceof的描述:
instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。
由这句话我们可以得出结论,只需要遍历原型链中是否有与之对应的构造原型即可

function newInstanceof(leftVaule, rightVaule) { 
    let rightProto = rightVaule.prototype; 
    // 取右表达式的 prototype 值 leftVaule = leftVaule.__proto__; 
    // 取左表达式的__proto__值 
    while (true) { 
        if (leftVaule === null) { 
            return false; 
        } 
        if (leftVaule === rightProto) { 
            return true; 
        } 
        leftVaule = leftVaule.__proto__ 
    } 
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值