this
is always function scoped in JavaScript (unless you pass in a context explicitly using call()
or apply()
. Therefore, in your private functions, this
no longer refers to the same this
as in the parent scope. An idiomatic way of handling this in JavaScript is to assign this
to a self
var in the parent scope. E.g.,
var myStorage = function(mymode) {
var self = this;
var mode = mymode;
function privateFunctionA() {
console.log(self);
};
...
};
Regarding this snippet:
myStorage.prototype.publicFunc = function() {
console.log(this.mode); // does this work?
}
You will need to assign mode
to this
back in your constructor (instead of as a var
). So, the constructor would now become:
var myStorage = function(mymode) {
var self = this;
this.mode = mymode;
function privateFunctionA() {
// works
console.log(self.mode);
};
...
};
And this.mode
will also work in your .publicFunc()
in this case.
As one more stylistic note, constructor functions in JavaScript usually use proper camel case (i.e., MyStorage
).