xin
xin

Reputation: 3

javascript closure __proto__

function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}
var add5 = makeAdder(5);
add5(2); //7;
add5(2).__proto__;  //0`

It makes sense. However, add5(2) is object? Why is there an 0?

Upvotes: 0

Views: 90

Answers (1)

Felix Kling
Felix Kling

Reputation: 816600

I don't know which environment you are running the code in, but this is what happens when you trying to access __proto__ on a number value: The value is temporarily converted to a number object (i.e. equivalent to calling new Number(7)). The prototype of that object is of course Number.prototype.

The spec says:

The Number prototype is itself a Number object; it has a [[NumberData]] internal slot with the value +0.

I can only assume that the environment you are using detects that add5(2).__proto__ is a number object and calls its valueOf method, which then returns 0:

console.log(Number.prototype.valueOf());

Upvotes: 2

Related Questions