ethan hur ethan hur - 3 months ago 6
Javascript Question

I have no idea Object(this) means

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?

Answer

As suggested in the comments on the code, this section is to accurately pollyfill the first steps documented in the spec.

  1. Let O be ToObject(this value).
  2. 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.

Comments