How to understand “hasOwnProperty” and “__proto__” in Js?

旧城冷巷雨未停 提交于 2019-12-08 05:44:32

问题


In ECMAScript,there is not __proto__ of an object:

 Array.hasOwnProperty('prototype')   //true
 var arr = new Array()
 arr.hasOwnProperty('__proto__')     //false

then, we can find:

Object.getOwnPropertyDescriptors(arr)

Output:

length:{value: 1, writable: true, enumerable: false, configurable: false}
__proto__:Object

So, I am confused: Does arr has his own property __proto__?

When I try to do follow things:

arr.unshift("2")

Where does Js engine find unshift method?

Is there any information let Js engine find unshift?


回答1:


Where does Js engine find unshift method?

On Array.prototype, from which arr inherits. There is an internal prototype chain link, often called [[prototype]], on every object. You can access it using Object.getPrototypeOf.

Object.getPrototypeOf(arr) == Array.prototype

So, I am confused: Does arr has his own property __proto__?

No, __proto__ is a setter/getter that is inherited from Object.prototype, it's not an own property. (You can find "__proto__" in arr, though). And it's deprecated. Best forget about it.

Why does Object.getOwnPropertyDescriptors(arr) output a __proto__?

Because the console uses this name to denote the internal prototype link. getOwnPropertyDescriptors returns an object, which naturally inherits from Object.prototype. Nothing special. You will find it in the empty object {} as well.



来源:https://stackoverflow.com/questions/48984407/how-to-understand-hasownproperty-and-proto-in-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!