1

I have seen a couple of JavaScript libraries that have this syntax at the beginning of the file. What does this statement mean, what is the value of getClass after this statement is run, and why is this needed? Also, what is the purpose of the semicolon at the beginning?

;(function (window) {
  // Convenience aliases.
  var getClass = {}.toString, isProperty, forEach, undef;

   // remaining function goes here
}
Punit Vora
  • 5,052
  • 4
  • 35
  • 44
  • The initial semicolon is just there to prevent accidents when code is combined and minified with other scripts. It does nothing, but if a preceding script is not properly terminated (JS being so friendly and all) it could cause an error. – wwwmarty Aug 13 '15 at 15:41
  • For the semicolon, see [What does the leading semicolon in JavaScript libraries do?](http://stackoverflow.com/q/1873983/1529630) – Oriol Aug 13 '15 at 15:48

2 Answers2

2

what is the value of getClass after this statement is run,

The same as {}.toString.

and why is this needed?

It isn't. The comment says it is a convenience alias.

Also, what is the purpose of the semicolon at the beginning?

So that if the script is concatenated with another script, and the previous script fails to include a ; after its last statement, it won't cause an error.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • - so basically in that one statement, we are declaring one variable getClass with a value of {}.toString, and also declaring the other variables isProperty, forEach, undef all of which have value undefined after this statement, correct? – Punit Vora Aug 13 '15 at 15:51
2

In ECMAScript 5, objects have an internal [[Class]] property, which according to 8.6.2 can only be accessed through Object.prototype.toString:

The value of a [[Class]] internal property is used internally to distinguish different kinds of objects. Note that this specification does not provide any means for a program to access that value except through Object.prototype.toString (see 15.2.4.2).

And {}.toString is a shortcut to that Object.prototype.toString.

For example, getClass can be used to test if an object is an Arguments object:

getClass.call(obj) === "[object Arguments]"
Oriol
  • 274,082
  • 63
  • 437
  • 513