Here is my latest discovery while experimenting with JS:
(function() { return this; }).call('string literal');
// => [String: 'string literal'] in V8
// => String { "string literal" } in FF
I stumbled on this while doing the following:
(function() { return this === 'string literal'; }).call('string literal');
// => false
Can anyone tell me why this
inside the function is not exactly what was passed as the first argument to call
?
Edit 1
What is the difference between string primitives and String objects in JavaScript? has been marked as a possible duplicate of my question.
While the answers to both questions are related to how JS wraps primitives inside Objects, I believe the questions, and their answers, are not identical.
My question was "why are the argument passed to call and the value of this inside the function different?", while the other question was "why is code block 1 faster than code block 2?"
The correct answer to my question was "because you did not use strict mode" while the answer to the other question was related to how fast data is accessed internally by engines implementing ECMAScript.
I hope this clarification is correct 😅
.call
internally invokes [[Call]]
, which performs
- Perform OrdinaryCallBindThis(F, calleeContext, thisArgument).
And OrdinaryCallBindThis
(which sets the this
value of the function that's going to be called) will wrap the new this
in an object in non-strict mode:
If thisMode is strict, let thisValue be thisArgument.
Else,
a. If thisArgument is undefined or null, then ...
b. Else, Let thisValue be ! ToObject(thisArgument).
In strict mode, you'll see that the string does not get wrapped in an object:
'use strict'; (function() { console.log(this); console.log(this === 'string literal'); }).call('string literal');
Since you are calling a method on the string primitive, it is automatically converted to a String Object.
The logs are how the two consoles render String Objects.
Further reading: What is the difference between string primitives and String objects in JavaScript?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.