Reputation: 43123
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?
Upvotes: 4
Views: 153
Reputation: 382716
My first question is: what is this kind of object (not defined as a function) called?
That is knows as object literal notation.
My second question is: What is this kind of object (defined as a function) called?
That is knows as function expression.
More Readings:
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?
You can use this
keyword to add properties or use prototype
property like this:
var example = function( message ) {
alert('message');
this.hello = function(){
alert('hello');
}
}
Or
var example = function( message ) {
alert('message');
}
example.prototype.hello = function(){
alert('hello');
}
var e = new example('hello');
e.hello();
When using this
, you need to use new
keyword to instantiate the object.
Interested readings on OOP:
Upvotes: 6