I am trying to organize my code using the revealing module pattern.
I have a very basic question about how to set up a setter method.
$(document).ready(function() {
var designs = (function() {
var curRow,
setCurRow = function(val) {
curRow = val;
},
initTable = function() {
setCurRow(0);
};
return {
curRow : curRow,
setCurRow : setCurRow,
initTable : initTable
}
}) ();
designs.initTable();
designs.setCurRow(someNewVal);
console.log(designs.curRow);
});
The problem is that i dont get the someNewVal in the console output, I get undefined instead! I have a feeling I am doing something pretty silly here.
You can also solve this in another way by understanding the scopes of the variables and functions involved.
When you return your object constructor
{ curRow: curRow ... }, that just initializes the object member namedcurRowto the value of the variablecurRowin the scope of the anonymous function; it doesn’t create any persistent connection between them.Once the anonymous function returns, calling
designs.setCurRowis updating thecurRowvariable in that scope exactly as you expect, but that variable is now totally inaccessible to the outside world — there is no connection between it and thecurRowmember of designs.You can solve this by making the
setCurRowmethod operate onthis.curRow, as in the other solutions. In that case you don’t need to makecurRowa variable in the original scope, since it’s entirely unused. The other solution is to add a ‘getter’ method to your current one:Because
getCurRowandsetCurRoware functions that are closed in the scope containing the variablevarRow, they can reach back into that scope and access and change variables that are only accessible within it.In this case making
curRowa member of the object you return is probably simpler, but the other way is useful too since you can use it to create effectively private members and methods.