I'm following Crockford's guide to private methods in Javascript, and I'm struggling with something. I'm trying to optimize this code
function Container(param) {
function dec() {
if (secret > 0) {
secret -= 1;
return true;
} else {
return false;
}
}
this.member = param;
var secret = 3;
var that = this;
this.service = function () {
return dec() ? that.member : null;
};
}
by defining the functions outside of the constructor so that a new function object isn't created each time a new instance is created.
I still have no idea of how to do this for those he refers to as private methods (any help is well appreciated). For those he calls privileged methods this is what I'm trying to do:
function Container(param) {
function dec() {
if (secret > 0) {
secret -= 1;
return true;
} else {
return false;
}
}
this.member = param;
var secret = 3;
var that = this;
}
Container.prototype.service = function() {
return dec() ? that.member : null;
};
but if I test it like this
d1 = new Container("content");
d1.service();
I get this error:
ReferenceError: dec is not defined
Does this mean there's no way of using the advantages of the private/privileged methods Crockford uses AND optimizing memory usage by linking all instances of the class to the same function object? I hope you'll prove me wrong.