1

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?

Shuai Li
  • 2,426
  • 4
  • 24
  • 43
  • 3
    `unshift` is a property of `Array.prototype`. – StackSlave Feb 26 '18 at 08:47
  • @PHPglue but `arr` has no property named `__proto__`, how does JsEngine find `Array.prototype.unshift` from `arr` ? – Shuai Li Feb 26 '18 at 08:51
  • `var arr = [];` is a new instance of an Array. Arrays have methods they inherit from `Array.prototype`, but they are not its own property. Array properties should be numeric indexes. – StackSlave Feb 26 '18 at 08:56
  • 1
    Possible duplicate of [Why is foo.hasOwnProperty('\_\_proto\_\_') equal to false?](https://stackoverflow.com/questions/24295785/why-is-foo-hasownproperty-proto-equal-to-false) – FredG Feb 26 '18 at 09:17

1 Answers1

2

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375