Note: this question is a follow up of the recently asked question JavaScript: automatic getters and setters in closures without eval? .
The gist of that question was as follows: "How can one automatically provide getters and setters for scoped variables in a closure - without the use of the eval
statement". There the poster, provided code demonstrating how to do so with eval
and the user gave the following answer which does not require eval
:
function myClosure() {
var instance = {};
var args = Array.prototype.slice.call(arguments);
args.forEach(function(arg) {
instance[arg] = function(d) {
if (!arguments.length) return arg;
arg = d;
return instance;
};
})
return instance;
};
This question is about how to have default values for the scoped variables which are to be set / get with the above function.
If we simply add a default value to the variable v3
we get the following:
function myClosure() {
var v3 = 2
var instance = {};
var args = Array.prototype.slice.call(arguments);
args.forEach(function(arg) {
instance[arg] = function(d) {
if (!arguments.length) return arg;
arg = d;
return instance;
};
})
return instance;
}
var test = myClosure("v1", "v2", "v3") // make setters/getters for all vars
test.v1(16).v2(2) // give new values to v1, v2
console.log(test.v1() + test.v2() + test.v3()) // try to add with default v3
// 18v3
I was not expecting that.
So how can I provide a default value to the variables?
Note: please build off the following implementation which generates the getters / setters on initialization (allowing the code author to pre-define all variables which should have getters and setters)
function myClosure() {
var instance = function () {};
var publicVariables =['v1', 'v2', 'v3']
function setup() {
var args = Array.prototype.slice.call(arguments);
// if called with a list, use the list, otherwise use the positional arguments
if (typeof args[0] == 'object' && args[0].length) { args = args[0] }
args.forEach(function(arg) {
instance[arg] = function(d) {
if (!arguments.length) return arg;
arg = d;
return instance;
};
})
}
setup(publicVariables)
// setup('v1', 'v2', 'v3') also works
return instance;
}
var test = myClosure()
test.v1(16).v2(2)
console.log(test.v1() + test.v2() + test.v3())
Question:
How to use default values in this set up (above code block) with automatic getters and setters?