Tuesday, 11 August 2009

JavaScript Objects (Pt 2)

All JavaScript functions are objects in their own right. This means that when you declare a function you are actually creating a new object and when you use the new keyword you are creating a new instance of the object associated with the stated function.

Example:
Foo(bar) {…} – creates a new object called Foo.
var myFoo = new Foo(bar); - creates a new instance of a Foo object and assigns it to myFoo.

If you create a function object function foo() {…} and then assign another function to it foo.bar = function() {…}; the bar method will only be available to foo and not to any new instances of foo. So you can do foo.bar but you cannot do var myFoo = new foo(); myFoo.bar(); I have not worked out why yet.