编程向导-JavaScript-基础语法-instanceof

梦里繁花落尽,此情未央,此意难忘,弦虽断,曲犹扬。!

与技术共同呼吸,与程序员共命运。世树科技 承“技驱动,理致胜”理念、国风编程。

instanceof

instanceof 运算符用于测试构造函数的 prototype 属性是否出现在对象的原型链中的任何位置。

代码示例:

target instanceof constructor;

检测类型

instanceof 可以检测某个对象是否是另一个对象的 实例

const Person = function () {};
const student = new Person();

console.log(student instanceof Person);
// true

instanceof 可以检测父类型。

function Person() {}
function Student() {}

const p = new Person();

// 继承原型
Student.prototype = p;

const s = new Student();

console.log(s instanceof Student);
// true
console.log(s instanceof Person);
// true

其他例子:

// 数字类型
console.log(1 instanceof Number);
// false
conosole.log(Infinity instanceof Number);
// false
console.log(Number(2) instanceof Number);

// 布尔值
console.log(true instanceof Boolean);
// false

// 字符串
console.log('' instanceof String);
// false

// 函数类型
const fn = () => console.log('Hello world!');
console.log(fn instanceof Function);
// true

模拟实现

function simulateInstanceof(left, right) {
  if (left === null || (typeof left !== 'object' && typeof left !== 'function')) return false;

  // 递归原型链
  while (true) {
    // Object.prototype.__proto__ === null
    if (left === null) return false;

    // 这里重点:当 left 严格等于 prototype 时,返回 true
    if (left === right.prototype) return true;

    left = left.__proto__;
  }
}

参考资料

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wtrees_松阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值