6
var example = function () {
  console.log(typeof this);
  return this;
};

In strict mode: example.call('test') # prints 'string'

Otherwise, example.call('test') # prints 'object'

However, console.log(example.call('test')) prints test (as you'd expect)

Why does Function.call change typeof 'test' === 'string' bound to this inside example?

hagemt
  • 328
  • 5
  • 12
  • 2
    It's not `call` that changes anything. It's sloppy mode that coerces the `this` value to an object (in here, a `String` object). – Bergi Aug 24 '15 at 20:14

1 Answers1

6

When using call() and setting the this argument to a primitive value, that primitive value is always converted to an object, so you get the string object instead of the primitive string

String {0: "t", 1: "e", 2: "s", 3: "t", length: 4, ...

The documentation for call() on MDN states that

thisArg
The value of this provided for the call to the function.
Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be converted to objects.

So in non-strict mode the primitive string value is converted to an object, this is also specified in the ECMA standard, Annex C

strict mode restriction and exceptions
If this is evaluated within strict mode code, then the this value is not coerced to an object.
A this value of null or undefined is not converted to the global object and primitive values are not converted to wrapper objects.
The this value passed via a function call (including calls made using Function.prototype.apply and Function.prototype.call) do not coerce the passed this value to an object

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Not a criticism of your post, but "boxed"? Why do people needlessly introduce meaningless jargon when the spec says the much more coherent "coerced to an object"? – RobG Aug 24 '15 at 20:48
  • @RobG - Who knows, it's copy/paste straight from MDN, which uses "boxed", so I continued to use that term. – adeneo Aug 24 '15 at 21:41
  • 1
    It doesn't say "boxed" anymore. ;-) – RobG Aug 24 '15 at 22:33