instanceof使用小结

109 阅读2分钟

「这是我参与2022首次更文挑战的第17天,活动详情查看:2022首次更文挑战

Hope is a good thing, maybe the best of things. And no good thing ever dies—— 《The Shawshank Redemption》

前言

上篇文章我们介绍了typeof的用法,我们可以使用typeof来确认一个变量的数据类型,例如:字符串类型('string')、布尔类型('boolean')、数字类型('number')、undefinedfunction

如果使用new操作符,除 Function 外的所有构造函数的类型都是 'object'。看下面的栗子:

var str = new String('String');
var num = new Number(66);

typeof str; // 'object'
typeof num; // 'object'

var func = new Function();

typeof func;  // 'function'

我们可以得出一个简单的结论:

  1. 基本类型数据,除 null(返回 object 类型)以外,都可以返回正确的结果类型。
  2. 引用类型数据,除 function(返回 function 类型) 以外,一律返回 object 类型。

那么如果要检测某个对象是什么类型,我们可以用 instanceof 来检测某个对象是不是另一个对象的实例。

instanceof 简介

instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

基本语法:

object instanceof constructor

instanceof 是用来判断 L 是否为 R 的实例,表达式为:L instanceof R,如果 L 是 R 的实例,则返回 true,否则返回 false。

function instance_of(L, R) { //L 表示左表达式,R 表示右表达式
  var O = R.prototype; // 取 R 的显示原型
  L = L.__proto__; // 取 L 的隐式原型
  while (true) {
    if (L === null)
      return false;
    if (O === L) // 这里重点:当 O 严格等于 L 时,返回 true
      return true;
    L = L.__proto__;
  }
}
// 代码示例来源于:https://blog.csdn.net/luzhaopan/article/details/107505745

在JavaScript中,万物皆对象(通过new操作符得到对象)

new String('sss') instanceof Object;  // true

new Boolean(true) instanceof Object; // true

new Number(2) instanceof Object; // true

new Function() instanceof Object; // true

new Array([]) instanceof Object; // true

instanceof 的常用例子

我们通常用来确认一个变量是不是数组。

检测 constructor.prototype 是否存在于参数 object 的原型链上。

var arr = [1, 2];

arr instanceof Array;

结语

如果这篇文章帮到了你,欢迎点赞👍和关注⭐️。

文章如有错误之处,希望在评论区指正🙏🙏

欢迎关注我的微信公众号,一起交流技术,微信搜索 🔍 :「 五十年以后