[英]Why does [1,2,3].prototype === Array.prototype return false?
I am playing with Prototype in my Chrome console.我正在 Chrome 控制台中玩 Prototype。 Wouldn't
[1,2,3].prototype === Array.prototype
equate to the same prototype since they both contain the same methods? [1,2,3].prototype === Array.prototype
等同于相同的原型,因为它们都包含相同的方法?
Non-Class objects don't have a prototype
property.非类对象没有
prototype
属性。 They instead have __proto__
.相反,他们有
__proto__
。 So this works:所以这有效:
[1,2,3].__proto__ == Array.prototype
//=> true
But it's deprecated.但它已被弃用。 If you really need to explicitly check the prototype, you can use this in modern JS engines:
如果你真的需要明确检查原型,你可以在现代 JS 引擎中使用它:
Object.getPrototypeOf([1,2,3]) == Array.prototype
In general, however, the way to check if an object is an instance of a class is to use instanceof
:但是,一般来说,检查对象是否是类的实例的方法是使用
instanceof
:
[1,2,3] instanceof Array
//=> true
Older javascript engines (and current, but is considered deprecated)较旧的 javascript 引擎(和当前的,但被认为已弃用)
[1,2,3].__proto__ === Array.prototype
Modern javascript engines (ie not IE)现代 javascript 引擎(即不是 IE)
Object.getPrototypeOf([1,2,3]) === Array.prototype
Add some extra points that deserves attention, __proto__
is an internal property that is not encouraged to use, and only need to be implemented in browser environment according to language specification, Object.getPrototypeOf()
is better.补充一些值得注意的地方,
__proto__
是内部属性,不鼓励使用,只需要按照语言规范在浏览器环境中实现, Object.getPrototypeOf()
更好。
Also you can do it by isPrototypeOf
:你也可以通过
isPrototypeOf
来做到:
Array.prototype.isPrototypeOf([1,2,3])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.