Could you propose any workarounds to implement a reference to variable using closures or any other tricks?
createReference = function() {
// TODO: how to
You have to use a string of the variable name but I think this is as close as you'll ever get in JavaScript:
var createReference = function (context, prop) {
return function () { return context[prop]; };
};
var x = 5;
var refX = createReference(this, 'x');
x = 6;
alert(refX()); // alerts 6
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:
var createReference = function (context, func) {
return function () { return func.call(context); }
};
Provider = function() {
};
Provider.prototype.x = 5;
Provider.prototype.getXRef = function() {
return createReference(this, function () { return this.x; });
// OR if you happen to be running in a
// JavaScript 1.8 environment like Firefox 3+,
// you can use "expression closures" for more
// concise code:
// return createReference(this, function () this.x);
};
Provider.prototype.incrementX = function() {
this.x = this.x + 1;
};
var provider = new Provider();
var refX = provider.getXRef();
provider.incrementX();
alert(refX()); // alerts 6