Note: there are a lot of questions regarding getters and setters in JavaScript (see Javascript Getters And Setters, Getters and Setters in a function (javascript), Getters and Setters in JavaScript (Correct syntax ?), automatic getter and setter(with validation) in javascript, etc). Most of these questions deal with Objects
, a few with Closures
and rather few of them with automatically producing getters and sets. This question deals with the later.
The answer to automatic getter and setter(with validation) in javascript is perhaps the closest for what I am looking for, but not-ideal for my use case.
Currently, in my closure I have the following:
function myClosure() {
var closureVar1, closureVar2
function do () { ... }
function setupSettersAndGetters() {
var closureVariables = ['closureVar1', 'closureVar2']
for (var i = 0; i < closuredVariables.length; i++) {
var currentClosureVariable = closureVariable[i]
var toEvaluateString = " \
do." + currentClosureVariable + " = function(value){ \
if(!arguments.length) return " + currentClosureVariable + "; \
" + currentClosureVariable + " = value; \
return setup; \
}; \
"
eval(toEvaluateString)
}
}
setupSettersAndGetters()
return do;
}
This works exactly as I like, e.g.
var test = myClosure()
test.closureVar1(10).closureVar2(2)
test.closureVar1() + test.closureVar2() // return 12
There is just the one "tiny" problem of using eval
which some people detest.
So my question is, is there a better way to handle this and allow for me to call the setter / getter by name, rather than using a string?
e.g. I could use an intermediate function such as:
test.sget('closureVar1', 10) // set closureVar1 to 10
test.sget('closureVar2') // get closureVar2
but even doing that I think I still need to use eval
? and I would prefer calling the name of the variable...
Thoughts?