How to understand “hasOwnProperty” and “__proto__”

2019-06-01 02:40发布

问题:

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.



标签: javascript v8