Javascript's classless OO model
The most important thing to keep in mind is that Javascript does not support the notion of 'class' as an explicitly defined language construct, unlike in C#, Java or C++. Javascript has been described as a 'prototypes'-based OO language which means that new objects can be created by copying from existing ones and then modified as needed by adding or deleting properties and methods on the fly. This offers far greater possibilities than using classes as rigid templates for object construction. That said, Javascript's more free-form facilities will allow you to program in a style equivalent to that of traditional class-based programming if you wish.
Creating objects in Javascript - via 'object literal' notation
The simplest method is to just create a hashtable (also known variously as map, dictionary or associative array). Since javascript objects are hashtables (and vice versa) whose keys serve as the object's properties, this is known as object literal notation. This is a very compact and succinct feature unique to Javascript. The key can be specified as a name or a string and the two methods are equivalent except that the latter lets you use a javascript keyword as the key (supposedly harmless).
cow={ pub1:1, "pub2":"publicvar #2" }
Creating objects in Javascript - via constructor function
One way to create multiple objects that share the same
properties (i.e. the equivalent of having a class template
in Javascript) is via a constructor function. This is
done by applying the new
keyword to a function.
new
creates a new, empty object instance
and (implicitly) sends this
to the function appearing after it.
This function can then access and modify the
object via this
, essentially acting as a constructor.
By convention, the function names for constructors should be capitalized.
function Cow() { var var1='publicvar #2' this["pub1"]=1 this.pub2=var1 } // instantiate cow1=new Cow()
Notice from the above that variables defined within the scope of the constructor function are effectively equvialent to private variables.
Modifying object properties
Because objects and hashtables are one and the same, and the hashtable keys are the object's properties, you can create and delete object properties at runtime.
cow.has_udder=true cow.moo=function() { alert('MOOO....!') }(try these again after clicking the buttons below)
In the example above, we assign a function to cow.moo
by
means of the
anonymous
function syntax.