Why does Modernizr do the following:
toString = {}.toString,
It's grabbing a local copy of the Object.prototype.toString
method which would allow it to make small speed improvements in the script. This also allows it to test that the toString
method exists.
Regards to comments:
Every name resolution there is a cost, in lookup-time (locals, globals, prototype-chaining) and creation (closure-scoped variable), so imaging 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 are having to resolve the values
variable, and walk the prototype chain to identify the member toString
, and then execute that.
Taking that above example, 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]));
}
Light applications won't really benefit too much from this, but larger frameworks, such as jQuery, etc, can improve the script performance quite significantly. IE I believe is one such browser where these small improvements can help quite a lot.
It checks whether under the given environment there is a toString property defined by default on an object. It doesn't do it on a new Object() because the Object may not itself be defined in the environment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With