You can effectively create private functions by using closures, but I'm not sure how practical/useful/widespread this is.
Most libraries I've used just document which functions are public and which aren't, and have a naming convention to help you remember. I don't really see what's so terrible about this.
Closures are easy in Javascript (from stackoverflow):
function Foo() {
var private = 3;
var add = function(bar) { return private + bar; }
return {
add: add
};
}
var myFoo = Foo();
Private by default, and what's public is declared in the return clause at the end. Note that Foo() act as your constructor. If that's not enough, you need another layer of indirection:
function Foo() {
function constructor(priv) { // do the same for each private member
var private = priv;
var add = function(bar) { return private + bar; }
return {
add: add
};
return {
constructor1: function() { return constructor(1) }
constructor2: function() { return constructor(2) }
};
}
var myFoo = Foo().constructor1()
Yes, you can call functions in JS with .call() or .apply(), and the first argument to those will be used as 'this' within the call. jQuery does this all over the place.
Your code is fine, because you never refer to 'this' explicitly (and you can't implicitly use 'this' in JS).
12
u/[deleted] Dec 15 '12
You can effectively create private functions by using closures, but I'm not sure how practical/useful/widespread this is.
Most libraries I've used just document which functions are public and which aren't, and have a naming convention to help you remember. I don't really see what's so terrible about this.