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
?
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 ofthis
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
andundefined
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
Ifthis
is evaluated within strict mode code, then thethis
value is not coerced to an object.
A this value ofnull
orundefined
is not converted to the global object and primitive values are not converted to wrapper objects.
Thethis
value passed via a function call (including calls made usingFunction.prototype.apply
andFunction.prototype.call
) do not coerce the passedthis
value to an object