instanceof 检查对象原型链是否包含构造函数的 prototype 对象,基于引用相等向上查找 [[Prototype]],不依赖 constructor 属性;原始值返回 false,null 无原型链,undefined 右侧非函数则报错;可由 Symbol.hasInstance 自定义行为。

instanceof 检查的是对象的原型链上是否包含构造函数的 prototype 对象。
很多人误以为 instanceof 是看 obj.constructor === Ctor,其实不是。constructor 可以被随意修改,完全不可靠。instanceof 的判断依据只有一条:沿着 obj 的 __proto__(即内部 [[Prototype]])一路向上查找,看能不能找到 Ctor.prototype 这个对象。
true
false
instanceof 不关心 Ctor.prototype 上有什么属性或方法,只关心“是不是同一个对象”。哪怕两个函数有完全一样的 prototype 内容,只要不是同一个对象实例,就不会匹配。
例如:
立即学习“Java免费学习笔记(深入)”;
function A() {}
function B() {}
B.prototype = Object.create(A.prototype); // 继承 A
const b = new B();
console.log(b instanceof A); // true —— 因为 B.prototype.__proto__ === A.prototype
console.log(b instanceof B); // true —— 因为 b.__proto__ === B.prototype
原始值(如字符串、数字、布尔)用 instanceof 总是返回 false,因为它们不是对象,没有原型链:
"hello" instanceof String → false
new String("hello") instanceof String → true
null instanceof Object → false(null 没有原型链)undefined instanceof Object → 报错(右侧必须是函数)如果构造函数上定义了静态方法 [Symbol.hasInstance](obj),instanceof 就会调用它,而不是走默认原型链查找。这是少数能覆盖默认行为的方式。
class MyArray {
static [Symbol.hasInstance](obj) {
return Array.isArray(obj) || (obj && typeof obj.length === 'number');
}
}
console.log([1,2] instanceof MyArray); // true
console.log({length: 5} instanceof MyArray); // true
以上就是JavaScript instanceof如何工作_它检查什么?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号