Search code examples
javascriptobjectprototype

Accessing __proto__ on a function returns a function


Consider the following code :

function objectFunction() {
  this.x = 2;
}
console.log(Object.keys(objectFunction));
console.log(objectFunction.__proto__, objectFunction.prototype);

Why am i getting a function on accessing __proto__ property on objectFunction since I can't find this property in the array I got using Object.keys(objectFunction) ?
Even when i call that returned function, it returns undefined.

When I tried running the above code, I got following : output
We have no keys on objectFunction, but I am able to access __proto__, which should not be the case. It should have returned undefined. I know from here that __proto__ is available only on instances and prototype on Functions or Objects.


Solution

  • __proto__ is a non-enumerable getter on Object.prototype which exists in objectFunction's prototype chain (objectFunction->Function.prototype->Object.prototype)

    So you are getting Function.prototype

    Which is a function because "The Function prototype object is specified to be a function object to ensure compatibility with ECMAScript code that was created prior to the ECMAScript 2015 specification" https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-properties-of-the-function-prototype-object