简体   繁体   中英

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?

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 (ie 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()); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM