Function.prototype.call alters typeof this, outside strict mode; why?

128 Views Asked by At
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?

1

There are 1 best solutions below

3
On BEST ANSWER

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