Does a Javascript object (this) use polygons?

I saw a Array.prototype.forEach() polyfill here , and I have a question about its implementation:

/*1*/   if (!Array.prototype.forEach)
/*2*/   {
/*3*/     Array.prototype.forEach = function(fun /*, thisArg */)
/*4*/     {
/*5*/       "use strict";
/*6*/   
/*7*/       if (this === void 0 || this === null)
/*8*/         throw new TypeError();
/*9*/   
/*10*/       var t = Object(this);
/*11*/       var len = t.length >>> 0;
/*12*/       if (typeof fun !== "function")
/*13*/         throw new TypeError();
/*14*/   
/*15*/       var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
/*16*/       for (var i = 0; i < len; i++)
/*17*/       {
/*18*/         if (i in t)
/*19*/           fun.call(thisArg, t[i], i, t);
/*20*/       }
/*21*/     };
/*22*/   }

Looking at line number 10: why did they use Object(this)?

When I searched for its use, I saw this :

The object constructor creates an object wrapper for a given value. If the value is null or undefined , it will create and return an empty object, otherwise it will return an object of the type that matches the given value. If the value is already an object, it will return the value.

Therefore, they wanted to check if this is null|| undefined.

Ok, but they already checked it in lines # 7- # 8!

Question:

( ), Object(this)?

+4
3

, , null || undefined.

.

. null undefined, , , . , .

, "foo" new String("foo").

, .length . , , ( ).

, Object(this)?

, # 1 forEach spec, ToObject . , [[Get]] [[HasProperty]].

, , .

+2

SO , , . 100% - . , , Object (this) var O = this;. forEach : ECMAScript forEach. , , , .. , .

OP (), . , . :

Array.prototype.forEach.call("abc", func);

abc. (this) abc :

String {0: "a", 1: "b", 2: "c", length: 3, [[PrimitiveValue]]: "abc"}

, abc "abc". polyfill :

kValue = O[k];

"abc" . undefined IE < 8.

, :   " IE7. undefined IE7. , .charAt(pos), : , , /". ()

Object (this) .

, :

" forEach , , Array, . forEach - ." ()

+1

undefined -ness. , .

, this , 42, Object(42), Number 42.

, , .

, polyfill . .length. ...

[].forEach.call("Hello!",function(letter) {console.log(letter);});
0

Source: https://habr.com/ru/post/1533122/


All Articles