What does Object(this) do?
-
22-07-2021 - |
Question
I noticed in several MDN Array method shims, such as this one on line 7, that they use the following syntax:
var t = Object(this);
Where this
is an array. Not only does it not hint in my validator, I’m also clueless as to what it does.
Can anyone shed a light?
Solution
As far as I can tell, the only use of it in there is to cover the case when you pass a string literal to Array.prototype.indexOf
. If you remove it and pass a string in you get an error:
TypeError: Cannot use 'in' operator to search for '0' in string
However, by casting the string literal to an instance of String
, you end up with an object with a numerical property for each character of the string, and since it's a normal object, you can use the in
operator on it and the method will return the index of the character in the string:
Array.prototype.indexOf.call("hello", "e"); // Returns 1
Here's an example with the cast to Object
, and here's an example without it.
In more general cases, passing anything to the Object
constructor will attempt to convert that thing to an object. So you can pass it a string literal and get an instance of String
back, or pass it a numeric literal and get an instance of Number
.