javascript como criar referência
ocê poderia propor soluções alternativas para implementar uma referência à variável usando fechamentos ou outros truque
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
E quanto a passar o contexto como primeiro argumento e passar o nome da variável (como string) e depois avaliar de alguma forma essa referência em contexto predefinido. Isso é viável?
Aqui está um cenário mais completo:
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());