0

Running the following code in Node.js (via repl.it) gives inconsistent results:

function F() {}

F.__proto__ == Function.prototype

Why does this sometimes result in true and sometimes in false? Is there a correct answer?

user200783
  • 13,722
  • 12
  • 69
  • 135
  • Noone stops you from using e.g. `Object.setPrototypeOf(F, { something: "else"});` – ASDFGerte Jan 11 '20 at 12:45
  • For what i undestand the `prototype` object became `__proto__` when the function is executed. https://stackoverflow.com/a/9959753/5781499 Take a look here ``` function F() {} F.prototype.foo = function(){} console.log(F.__proto__ === F.prototype); console.log((new F()).__proto__ === F.prototype) ``` – Marc Jan 11 '20 at 13:00
  • 1
    What do you mean by "sometimes"? Please also show an example where it does not. For any unaltered regular `function`, it should be equal. – Bergi Jan 11 '20 at 14:53
  • 1
    @Bergi - "For any unaltered regular function, it should be equal." Thanks, that's what I wanted to know. – user200783 Jan 12 '20 at 02:51
  • @Bergi - "Please also show an example where it does not." See my comment on frogatto's answer below. – user200783 Jan 12 '20 at 02:52

1 Answers1

2

function F() {} creates an object called F that is instanceof Function. This instance object has a prototype link to Function.prototype object. This link is not fixed, you can change prototype of an object after it's been created.

function F() {}

console.log('original F:', Object.getPrototypeOf(F) === Function.prototype);

Object.setPrototypeOf(F, {});

console.log('after prototype change:', Object.getPrototypeOf(F) === Function.prototype);
frogatto
  • 28,539
  • 11
  • 83
  • 129
  • Thanks. The result of running your code here is "true, false", but if I run it [using repl.it](https://repl.it/repls/NeedyCoordinatedCompiler), the result is "false, false". Do you know why these results are different? – user200783 Jan 12 '20 at 02:50
  • 1
    @user200783: Yeah, repl.it isn’t reflective of a normal environment here (and they should fix it). Judging by `console.log(new Error().stack)` (and the usual way this occurs), they’re running a script in a new context using the [vm module](https://nodejs.org/api/vm.html), but using the globals from the parent context, when those globals are normally different across contexts. Compare `({}.constructor)("") instanceof String` (false in current repl.it, should be true when using the current context’s `String`). – Ry- Jan 12 '20 at 07:05