Javascript's Object(this) usages in polyfills? -


i saw here array.prototype.foreach()'s polyfill , have question implementation :

/*1*/   if (!array.prototype.foreach) /*2*/   { /*3*/     array.prototype.foreach = function(fun /*, thisarg */) /*4*/     { /*5*/       "use strict"; /*6*/    /*7*/       if (this === void 0 || === 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*/       (var = 0; < len; i++) /*17*/       { /*18*/         if (i in t) /*19*/           fun.call(thisarg, t[i], i, t); /*20*/       } /*21*/     }; /*22*/   } 

looking @ line #10 : why did use object(this) ?

as searched usages saw this :

the object constructor creates object wrapper given value. if value null or undefined, create , return empty object, otherwise, return object of type corresponds given value. if value object already, return value.

so wanted check if it's null || undefined .

ok , already checked in lines #7-#8 !

question :

what reason (which i'm missing) used object(this) ?

so wanted check if it's null || undefined.

no. purpose is

the object constructor creates object wrapper given value. if value null or undefined, create , return empty object, otherwise, it return object of type corresponds given value. if value object already, return value.

it convert primitives objects, "foo" new string("foo").

this strictly not necessary, because property access of .length , indices convert primitive object anyway. make difference when third callback parameter used, can expect object there (and same 1 each invocation).

what reason used object(this)?

mostly reproduce step #1 of foreach spec, call toobject on argument. in spec required able use [[get]] , [[hasproperty]] internal methods on it.

also, converting primitive object once gain speed.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -