Skip to content Skip to sidebar Skip to footer

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 nu

Solution 1:

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.

Solution 2:

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.

Post a Comment for "I Have No Idea Object(this) Means"