var obj = {x : 2};
eval.call(obj, ‘x’); // ReferenceError: x is not defined
How to change last line to get value by variable name?
Clarification
‘x’ – any expression in some obj context, possibly not a obj parameter
Original problem
/**
* Guards 'this' when delegating method as a callback to others. Arguments aren't known beforehand and will be provided by consumer.
*/
delegate = function(context, func) {
return function() {
var args = [];
for ( var i = 0; i < arguments.length; i++)
args.push(arguments[i]);
func.apply(context, args);
};
};
reference = function (context, 'expression to evaluete to get reference value') {
... TODO
};
‘delegate’ – delegates function call, how to ‘delegate a reference’ with possibility to ‘dereference’ in different context?
Updates
here is 2 possibilities to use eval:
1. eval.call(null, ‘evaluate expression in global context’);
2. eval(‘evaluate expression in context where eval function was called’)
3. how to eval in some predefined ‘context’ ?
I want to mimic C++ reference when you can put it in any context and ‘dereference’ to value (but when in moment you dereference it value could be changed and you should get new value). Like in javascript you put object as function argument and anytime you get obj.someproperty you’ll get newest someproperty value (if it was changed). But this will not work when you will try to pass a primitive or what if whole object will be changed by some other. How to ‘pass a reference’ to ‘whole object’ to some other context?
Got clear understanding what I want 🙂
javascript how to create reference
What I was looking for:
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());
Tanks Brianpeiris!
This should do it, no need for eval: