D
David Karr
I noticed a new JavaScript practice today that seems curious, and I'm
trying to imagine when you might use this. The book I saw this in
refers to it as "self-instantiating classes". I understand basically
how it works, but I've never seen this done before in this way, so I'm
wondering what use it might be.
The following is an excerpt that illustrates the practice (the key is
the "new" on the function):
------------------------
// Example of a self-instantiating class
var Inbox = new function() {
this.messageCount = 0;
this.refresh = function() {
return true;
}
}();
// The new keyword and braces force the function to immediately
execute,
// meaning the Inbox variable now contains the single object instance,
// not the class
// Example method call on the single instance of Inbox
Inbox.refresh();
----------------------
What happens here is that executing "Inbox.refresh()" first executes
the function that you might call "Inbox", apparently creating a new
instance of the function, then calls the "refresh()" function on that
object. I see what it does, it just seems unusual.
trying to imagine when you might use this. The book I saw this in
refers to it as "self-instantiating classes". I understand basically
how it works, but I've never seen this done before in this way, so I'm
wondering what use it might be.
The following is an excerpt that illustrates the practice (the key is
the "new" on the function):
------------------------
// Example of a self-instantiating class
var Inbox = new function() {
this.messageCount = 0;
this.refresh = function() {
return true;
}
}();
// The new keyword and braces force the function to immediately
execute,
// meaning the Inbox variable now contains the single object instance,
// not the class
// Example method call on the single instance of Inbox
Inbox.refresh();
----------------------
What happens here is that executing "Inbox.refresh()" first executes
the function that you might call "Inbox", apparently creating a new
instance of the function, then calls the "refresh()" function on that
object. I see what it does, it just seems unusual.