简体   繁体   中英

When using bind() on a Javascript number, what does the console.log() output represent?

I came across a tutorial on bind() and the output is [Number: 1] . Why is the number represented like this when logged as the context of the bind function?

 const func = function() { console.log(this) }.bind(1); func();

Thanks!

Bind sets the "this" property to whatever the argument is that it is passed. In this case, since 1 is a primitive it is wrapped in the Number object (this is how JS handles primitives being used as objects) so the this context is the Number object containing 1.

The first parameter of bind is the target to bind to the function.

In this case a number literal is supplied.

Internally, bind boxes the number literal into a Number object, equivalent to Number(1) .

This object is then printed to the console.

Where, internally, bind performs the boxing, I am unsure.

In the spec the operation BoundFunctionCreate assigns the new target to the [[BoundThis]] internal slot.

9.4.1.3 BoundFunctionCreate ( targetFunction, boundThis, boundArgs )

The abstract operation BoundFunctionCreate with arguments targetFunction, boundThis and boundArgs is used to specify the creation of new Bound Function exotic objects. It performs the following steps:

  1. Assert: Type(targetFunction) is Object.

  2. Let proto be ? targetFunction.[GetPrototypeOf].

  3. Let obj be a newly created object.

  4. Set obj's essential internal methods to the default ordinary object definitions specified in 9.1.

  5. Set obj.[[Call]] as described in 9.4.1.1.

  6. If IsConstructor(targetFunction) is true, then

  7. Set obj.[[Construct]] as described in 9.4.1.2.

  8. Set obj.[[Prototype]] to proto.

  9. Set obj.[[Extensible]] to true.

  10. Set obj.[[BoundTargetFunction]] to targetFunction.

  11. Set obj.[[BoundThis]] to boundThis.

  12. Set obj.[[BoundArguments]] to boundArgs.

  13. Return obj.

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