JavaScript 中的 typeof 和 instanceof

使用 typeofinstanceof 都可检测变量类型,typeof 可以判断基本数据类型以及函数,但是无法判断数组、对象以及 null

typeof

var num = 123,
  str = "123",
  flag = true,
  unde = undefined;
console.log(typeof num);
console.log(typeof str);
console.log(typeof flag);
console.log(typeof unde);
​
var arr = [],
  obj = {},
  test = function () {},
  nu = null;
console.log(typeof arr);
console.log(typeof obj);
console.log(typeof test);
console.log(typeof nu);

上面的代码中判断 arrobjnu 返回的都是 object,无法具体的判断数据类型

instanceof

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

function Person() {}
​
let person = new Person();
​
console.log(person instanceof Person); //  true

实现 instanceof

/**
 *
 * instanceof 实现原理
 *
 * 检测构造函数的原型是否出现在实例的原型链上
 *
 * @param {*} letfValue 实例对象
 * @param {*} rightValue 构造函数
 */
function new_instanceof_of(letfValue, rightValue) {
  let rightProto = rightValue.prototype,
    leftProto = letfValue.__proto__;
  while (true) {
    if (leftProto === null) {
      return false;
    }
    if (leftProto === rightProto) {
      return true;
    }
    leftProto = leftProto.__proto__;
  }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值