Here is my module:
MyModule = (function () {
var myModule = function MyModule(strInput) {
if (false === (this instanceof MyModule)) {
return new MyModule();
}
str = strInput;
}
var str;
myModule.prototype.getStr = function () {
return str;
}
myModule.prototype.test = function () {
var testModule = new MyModule("testInside");
console.log(testModule.getStr());
console.log(str);
}
return myModule;
}());
Here is how I test my module:
document.getElementById("Button").onclick = function () {
var module = new MyModule("input");
module.test();
}
This code returns:
testInside
testInside
to the console.log, but what I expect is:
testInside
input
like I do in c# or java when I build a new class inside the same class.
If you want to keep the
strprivate, you can make it like this:In this way the
stris in the inner closure, so it’s like an instance/object variable in other languages. If you put it in the outer closure it will act like a static/class variable. In both cases, the methods of the myModule object still can access it, but it’s not visible from the outside.