I have no idea what the object (this) means

At https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/fill

there is a string 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 cannot find the need to assign O as Object (this).

Is it written for readability only or is there any specific reason for the assignment?

+5
source share
2 answers

As suggested in the code comments, this section should accurately supplement the first steps described in the specification .

  • Let O be TOObject (this value).
  • ReturnIfAbrupt (O).

Despite the fact that it is a little out of order, it does fucntion ToObject(this value) :

 var O = Object(this); 

Basically, if it is called for a non-object, the non-object should be dropped in Object .

For example, if we were to run this bit of mostly meaningless code in the JavaScript engine that supports this method, we will see that an instance of the Number object is returned.

 Array.prototype.fill.call(123); 

This line will provide the same result from the polyfill.

+3
source

The object constructor returns its argument when the argument is already an object. If it is not an object, it returns an “objectified” version of the argument: an instance of String if it is a string, an instance of Number if it is a number, etc.

The function in question is a bit strange, and in particular, the value of this will usually be an object. This should not be, but you need to get out of your way to get to the internal polyfill values ​​with this value, which is not an object.

+1
source

All Articles