In https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/fill
there is a line like
// Steps 1-2.
if (this == null) {
throw new TypeError('this is null or not defined');
}
var O = Object(this); // <- WHAT IS THIS???????????
// Steps 3-5.
var len = O.length >>> 0;
// Steps 6-7.
var start = arguments[1];
var relativeStart = start >> 0;
// Step 8.
var k = relativeStart < 0 ?
Math.max(len + relativeStart, 0) :
Math.min(relativeStart, len);
// Steps 9-10.
var end = arguments[2];
var relativeEnd = end === undefined ?
len : end >> 0;
// Step 11.
var final = relativeEnd < 0 ?
Math.max(len + relativeEnd, 0) :
Math.min(relativeEnd, len);
// Step 12.
while (k < final) {
O[k] = value;
k++;
}
// Step 13.
return O;
and I can't find any necessity to assign O as Object(this).
Is it written just for readability or is there any specific reason for assigning?
As suggested in the comments on the code, this section is to accurately pollyfill the first steps documented in the spec.
- Let O be ToObject(this value).
- ReturnIfAbrupt(O).
Though a bit out-of-order, this is performing the fucntion of ToObject(this value)
:
var O = Object(this);
Basically, if it is called on a non-object, the non-object should be cast to an Object
.
For example, if we were to run this bit of mostly-nonsensical code in a JavaScript engine which natively supports this method, we would see a Number
object instance gets returned.
Array.prototype.fill.call(123);
That line would ensure the same result from the polyfill.
The Object constructor returns its argument when the argument is already an object. If it's not an object, it returns the "objectified" version of the argument: a String instance if it's a string, a Number instance if it's a number, etc.
The function in question is a little weird, and in particular the value of this
will usually be an object anyway. It doesn't have to be, but you kind-of have to go out of your way to get to the innards of the polyfill with a this
value that isn't 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