instanceof

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

但这种方式弊端比较多

  1. 对于基本数据类型来说,字面量方式创建出来的结果和实例方式创建出来的是有区别的
1 instanceof Number //false
new Number(1) instanceof Number //true
  1. 只要在当前实例的原型链上,我们用其检测出来的结果都是 true。在类的原型继承中,我们最后检测出来的结果未必准确。
let fn= function(){}
fn instanceof Function //false
fn instanceof Object //true
  1. 对于特殊的数据类型 nullundefined,他们的所属类是 Null 和 Undefined,但是浏览器把这两个类保护起来了,不允许我们在外面访问使用
undefined instanceof undefined
null instanceof null
// Uncaught TypeError: Right-hand side of 'instanceof' is not an object

原理

instanceof 检测一个对象 A 是不是另一个对象 B 的实例的原理是:
查看 对象 B 的 prototype 指向的对象是否在 对象 A 的 prototype 链上。
如果在,则返回 true, 如果不在则返回 false

let myinstanceof = function(left, right) {
  let target = left.prototype;
  while (target) {
    if (target.__proto__ === right.prototype) return true;
    target = target.__proto__;
  }
  return false;
};