<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>instanceof</title> </head> <body> <script> /*参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/instanceof * 知识点: * 1.语法 object instanceof constructor 2.参数 object 要检测的对象. constructor 某个构造函数 3.描述 instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。 * */ // 1. function Car(make, model, year) { this.make = make; this.model = model; this.year = year; console.log("this:", this); // this: Car {make: "Honda", model: "Accord", year: 1998} } let auto = new Car('Honda', 'Accord', 1998); console.log(auto instanceof Car); // true console.log(auto instanceof Object); // true // 2. // 定义构造函数 function C() { } function D() { } let o = new C(); console.log(''); // console.log("C:", C); // console.log("o:", o); // console.log(Object.getPrototypeOf(o)); // console.log(C.prototype); console.log(o instanceof C); // true,因为 Object.getPrototypeOf(o) === C.prototype // console.log(D.prototype); console.log(o instanceof D); // false,因为 D.prototype不在o的原型链上 console.log(o instanceof Object); // true,因为Object.prototype.isPrototypeOf(o)返回true console.log(C.prototype instanceof Object); // true,同上 C.prototype = {}; let o2 = new C(); // console.log("o:", o); // console.log("o2:", o2); // console.log("C:", C); console.log(o2 instanceof C); // true console.log(o instanceof C); // false,C.prototype指向了一个空对象,这个空对象不在o的原型链上. D.prototype = new C(); // 继承 let o3 = new D(); console.log(o3 instanceof D); // true console.log(o3 instanceof C); // true 因为C.prototype现在在o3的原型链上 </script> </body> </html>
js instanceof.html
最新推荐文章于 2024-01-10 14:30:34 发布