原理instanceof
instanceof会检查原型链(proto)属性上存不存在类的prototype属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| function instanceOf(L, R) { let O = R.prototype; L = L.__proto__; while(true) { if(L === null) { return false; } else if (L === O) { return true; } else { L = L.__proto__ } } }
class Car { constructor(color) { this.color = color; } }
class Cruze extends Car { constructor(color) { super(color); } } const cruze = new Cruze("白色");
console.log(cruze); console.log(instanceOf(cruze, Cruze)); console.log(instanceOf(cruze, Car));
|