Could you propose any workarounds to implement a reference to variable using closures or any other tricks?
createReference = function() {
// TODO: how to implement?
};
var x = 5;
var refX = createReference(x); // could be any parameters needed to implement the logic
x = 6;
alert(refX()); // should alert 6
What about passing context as first argument and pass variable name (as string) and later somehow evaluate that reference in predefined context. Is this feasible?
Here’s a more complete scenario:
createReference = function(context, prop) {
return function() {
return context[prop];
};
};
Provider = function() {
};
Provider.prototype.x = 5;
Provider.prototype.getXRef = function() {
return createReference(this, 'x');
};
Provider.prototype.incrementX = function() {
this.x = this.x + 1;
};
var provider = new Provider();
var refX = provider.getXRef();
provider.incrementX();
alert(refX());
You have to use a string of the variable name but I think this is as close as you’ll ever get in JavaScript:
Edit:
In your updated scenario it would be better to use a closure directly, so that you don’t have to use a string of the variable name: