Punit Vora
Punit Vora

Reputation: 5198

What is the purpose of creating aliases in JavaScript? What does this JavaScript statement do?

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
}

Upvotes: 1

Views: 78

Answers (2)

Oriol
Oriol

Reputation: 288480

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]"

Upvotes: 2

Quentin
Quentin

Reputation: 943999

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.

Upvotes: 2

Related Questions