I have no idea Object(this) means

前端 未结 2 835
借酒劲吻你
借酒劲吻你 2021-01-13 12:39

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) {
           


        
相关标签:
2条回答
  • 2021-01-13 12:47

    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.

    0 讨论(0)
  • 2021-01-13 12:59

    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.

    0 讨论(0)
提交回复
热议问题