Tuesday 2 April 2013

[[Class]] IN JAVASCRIPT

Class in JavaScript??
The ECMA standard specifies internal properties some of which are common to all JavaScript objects. These are invisible properties which exist solely for specification purposes. The [[Class]] is one of such. Some others include [[Prototype]], [[Get]], [[Put]] etc. For a complete set of these properties see the ECMA script standard. These properties are used to define the semantics of the object values.

[[Class]]

The [[Class]] property stores a string  which defines the kind of object. Function objects  have the [[Class]] value  "Function", Date objects have the [[Class]] value "Date", Object objects have the [[Class]] value "Object" and so on. The table below (taken from Dave Herman's book "Effective JavaScript") shows the [[Class]] values and corresponding constructors matching the types of objects.

[[Class]]Construction
"Array" new Array(), [ ]
"Boolean" new Boolean()
"Date" new Date()
"Error" new Error(), new RangeError() etc
"Function" new Function()
"JSON" JSON
"Math" Math
"Number" new Number()
"Object" new Object(), {}
"RegExp" new RegExp()
"String" new String()

Determine the [[Class]] value in JavaScript

In JavaScript the "Object.prototype.toString" method returns the string representation of the object. Internally it queries the [[Class]] property and uses its value as part of  the string generated for the receiver. This can be seen in the example below



These internal properties are essential in defining the behaviour of objects, An example would be if an object is not a pure array (ie [[Class]] property value is specified as “Array”) there are no guarantees on the behaviour of its methods and the value of its properties .
In the example below the concat method of the array object depends on the value of the [[Class]] property, if an argument passed into the method is a true array it concatenates its contents to that of the result else it adds it as a single object.
Example:


References

1. ECMA Script Standard
2. Effective Javascript by Dave Herman