Modernizr toString

Why Modernizr does the following:

toString = {}.toString, 
+4
source share
2 answers

It captures a local copy of the Object.prototype.toString method, which allows you to make small speed improvements in the script. It also allows you to check if the toString method exists.

Regarding comments:

Each name resolution has a cost during the search (locals, globals, prototype-chaining) and creation (a variable with a closed scope), therefore, to display the following code:

 var values = // Create some object here. for (var i = 0; i < count; i++) { console.log(values[i].toString()); } 

For each iteration of the look, we need to enable the values variable and go through the prototype chain to identify the toString element, and then do it.

Taking this example above, we could do the following:

 var toString = {}.toString, values = // Create some object here. for (var i = 0; i < count; i++) { console.log(toString.call(values[i])); } 

Or even further:

 var toString = {}.toString, log = console.log, values = // Create some object here. for (var i = 0; i < count; i++) { log.call(console, toString.call(values[i])); } 

Lightweight applications may not really benefit much from this, but large frameworks such as jQuery, etc., can significantly improve script performance. IE, I believe, is one of those browsers where these small improvements can help quite a lot.

+7
source

It checks if the toString property defined by default for the object exists in this environment. It does not do this on the new object (), because the object cannot be defined in the environment.

+1
source

All Articles