Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modernizr toString

Why does Modernizr do the following:

toString = {}.toString,
like image 546
Lydon Ch Avatar asked Feb 20 '23 08:02

Lydon Ch


2 Answers

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.

like image 67
Matthew Abbott Avatar answered Mar 05 '23 10:03

Matthew Abbott


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.

like image 28
Konstantin Dinev Avatar answered Mar 05 '23 11:03

Konstantin Dinev