What's the point of “var t = Object(this)” in the official implementation of forEach?

后端 未结 3 1390
一个人的身影
一个人的身影 2021-01-31 06:05

According to the MDC, the ECMA-262, 5th edition gives the implementation of forEach as:

if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun          


        
3条回答
  •  抹茶落季
    2021-01-31 06:33

    The probable reason is s9.9 of ECMA-262, about the abstract ToObject operation (as mentioned by @CMS).

    When called on null or an undefined value it forces the throwing of a TypeError, but those are already trapped by the previous lines.

    However if you were to call:

    Array.prototype.forEach.call("123", func() { ... } )
    

    this would fail if it weren't for the type coercion. In particular you can't call index in this if this is a string, but you can call it on the result of ToObject.

    This text from 15.4.4.18 is probably relevant:

    The forEach function is intentionally generic; it does not require that its this value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method. Whether the forEach function can be applied successfully to a host object is implementation-dependent.

提交回复
热议问题