instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。 语法:object instanceof constructor 参数 object:某个实例对象 constructor:某个构造函数 描述:instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。 实现原理:查看对象B的prototype指向的对象是否在对象A的[[prototype]]链上。如果在,则返回true,如果不在则返回false
function Car(make,model,year){this.make = make;this.model = model;this.year = year;}const auto = new Car('honda','Accord',1998);console.log('-----instanceof------')console.log(auto instanceof Car)console.log(auto instanceof Object)//Object.getPrototypeOf()方法返回指定对象的原型(内部[[Prototype]]属性的值)。function myInstanceof(obj,cons){if(typeof obj !=='object' ||!obj)return false;const _obj = Object.getPrototypeOf(obj);//obj.__proto__不推荐使用if(_obj!==cons.prototype){return myInstanceof(_obj,cons)}else{return true;}}console.log('-----myInstanceof------')console.log(myInstanceof(auto,Car))console.log(myInstanceof(auto,Object))console.log('myInstanceof([], Array):',myInstanceof([], Array))console.log('myInstanceof({}, Object):',myInstanceof({}, Object))

