1

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!

jjkl
  • 353
  • 6
  • 15

2 Answers2

1

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.

Jawi
  • 360
  • 1
  • 8
  • Thanks. How should I interpret the output syntax though? It's not an array but it has square brackets? On the other hand, the colon leads me to think, as your answer suggests, an object. – jjkl Feb 12 '20 at 18:40
  • @jjkl I'm not as sure about this one, but the behavior is the same whether the bind argument is 1 or new Number(1). I imagine it relates to how this is treated internally by the constructor/boxing process. – Jawi Feb 12 '20 at 19:46
  • @jjkl it is just the way Nodejs represents the Object [Number: 1], but chrome/firefox represents it as Number {1} in the dev console – sney2002 Feb 12 '20 at 20:02
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.

Community
  • 1
  • 1
Ben Aston
  • 53,718
  • 65
  • 205
  • 331