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
?
A function prototype is a definition that is used to perform type checking on function calls when the EGL system code does not have access to the function itself. A function prototype begins with the keyword function, then lists the function name, its parameters (if any), and return value (if any).
apply and Function. prototype. call are methods that allow you to call a function with a specific this value and arguments. The main difference between the two is that apply lets you pass in an array of arguments, while call requires you to list the arguments one by one.
In strict mode, it is now undefined . When a function was called with call or apply , if the value was a primitive value, this one was boxed into an object (or the global object for undefined and null ). In strict mode, the value is passed directly without conversion or replacement.
The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With