By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,984 Members | 997 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,984 IT Pros & Developers. It's quick & easy.

Expose multiple global functions from within a closure?

P: n/a
Let's say I want to create two (or more) global functions from within a
closure, so they can both share some "private" variables and methods. What
is the recommended way to do this?

(function(){
var message = "hello!";
window.showMessage = function() {
alert(message);
}
window.setMessage = function(str) {
message = str;
}
})();

Assuming a browser context (and therefore window. global ref) is this the
best way to do it?

I realize I could create it as a class with these as "static methods" of the
class, but I am re-writing someone else's code and need to maintain the same
global function interface (for now).

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Jan 7 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On 07/01/2006 14:45, Matt Kruse wrote:
(function(){
var message = "hello!";
window.showMessage = function() {
alert(message);
}
window.setMessage = function(str) {
message = str;
}
})();

Assuming a browser context (and therefore window. global ref) is this the
best way to do it?


[snip]

If I had to use globals, I'd still declare them and omit the window
reference:

var showMessage, setMessage;

(function() {
var message = 'Hello!';

showMessage = function() {
alert(message);
};
setMessage = function(string) {
message = string;
};
})();

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Jan 7 '06 #2

P: n/a
Matt Kruse wrote:
Let's say I want to create two (or more) global functions from within a
closure, so they can both share some "private" variables and methods. What
is the recommended way to do this?

(function(){
var message = "hello!";
window.showMessage = function() {
alert(message);
}
window.setMessage = function(str) {
message = str;
}
})();

Assuming a browser context (and therefore window. global ref) is this the
best way to do it?

I realize I could create it as a class with these as "static methods" of the
class, but I am re-writing someone else's code and need to maintain the same
global function interface (for now).


What works. However, there are some advantages to reducing your
dependence on global variables. I think it is best to have a single
global that is the container for your stuff.

var my = function () {
var message = "hello!";
return {
showMessage: function () {
alert(message);
},
setMessage: function (str) {
message = str;
}
};
}();

In that pattern, you return an object which you stuff in a global
variable.

http://www.crockford.com/javascript/
Jan 7 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.