Relative JS newbie here trying to understand the difference between two ways of defining a JS object...
In certain cases I have seen examples of what I would call "namespace" objects or "handlers" that might look something like this:
var example = {
message: null,
setup: function( message ) {
example.message = message;
alert( message );
}
}
I might use something like this to group some related functions. If I were to call example('foo!') I would expect an alert message with foo! to appear, and thereafer if I called example.message I would expect it to return foo!.
My first question is: what is this kind of object (not defined as a function) called?
I use objects like this a lot in my sites, as handlers to setup a bunch of bindings for ajax interactions etc. I've been trying to learn about object-oriented javascript, and have been doing some reading (1,2). In the Mozilla docs it's suggested that objects should be defined as functions, so more like this:
var example = function( message ) {
....
}
My second question is: What is this kind of object (defined as a function) called?
I don't really understand the difference between the two so I'm having a number of issues, which raises question 3:
If you define an object as a function, how do you define properties on the object if you don't necessarily want them to execute when it is instantiated?
Ie. if I do this:
var example = function( message ) {
alert('message');
}
Then I know that example('foo!') will trigger an alert with foo!. But, how do I define other properties or methods on the object to access and/or call later?