Array instanceof Array 为 false的原理
时间: 2023-10-29 22:44:36 浏览: 126
数组是一种特殊的对象,其原型链上除了 Object.prototype 还有 Array.prototype。Array instanceof Array 为 false 的原因是因为 instanceof 运算符会沿着原型链向上查找,判断一个对象的原型链上是否包含指定的构造函数,而数组的原型链上除了 Array 构造函数外还包含了 Object 构造函数,因此 instanceof 运算符在查找时会返回 false。换句话说,数组虽然是 Array 的实例,但它也是 Object 的实例,因此 instanceof 运算符不能完全识别它。
相关问题
Array instanceof Array为false;Array instanceof Object为true的原理
这个问题涉及到JavaScript中的对象和原型链。在JavaScript中,每个对象都有一个原型链,它是由一个或多个原型对象组成的链。原型对象是一个普通的JavaScript对象,它包含该对象的属性和方法。当你访问一个对象的属性或方法时,JavaScript引擎会首先查找该对象自身是否具有该属性或方法,如果没有,则会沿着原型链向上查找,直到找到该属性或方法或者到达原型链的末尾为止。
在JavaScript中,Array是一个构造函数,它用于创建数组对象。当你使用new关键字创建一个数组对象时,JavaScript引擎会执行以下步骤:
1. 创建一个新的空对象。
2. 将该对象的原型指向Array.prototype。
3. 执行Array函数体内的代码,并将this绑定到该对象上。
4. 返回该对象。
因此,当你创建一个数组对象时,该对象会具有Array.prototype中定义的属性和方法,同时它的原型链中也包含了Array.prototype。因此,当你使用Array instanceof Object时,它会返回true,因为数组对象是Object的子类,它继承了Object.prototype中的属性和方法。
但是,当你使用Array instanceof Array时,它会返回false。这是因为数组对象并不是Array.prototype的实例,它只是继承了Array.prototype中的属性和方法。Array.prototype并不是一个数组对象,它只是一个普通的JavaScript对象。因此,当你使用Array instanceof Array时,它会返回false,因为数组对象并不是Array.prototype的实例,它只是继承了Array.prototype中的属性和方法。
Array instanceof Object 为true,Array instanceof Array 为false Object instanceof Object 为true,原理解释
这是因为在JavaScript中,所有的对象都是Object类型的实例,包括Array类型。因此,Array instanceof Object 返回true。
但是,Array也是一个特殊的对象类型,它继承自Object,但拥有自己的属性和方法。因此,Array instanceof Array 返回false,因为Array并不是Array类型的实例,而是Object类型的实例。
同样地,Object instanceof Object 返回true,因为Object本身就是Object类型的实例。
阅读全文
相关推荐
















