1

In the function below, I want to pass two arguments. instance refers to an object, prop refers to an object property name.

door.x = 20; // door['x'] refers to the same
key(door, 'x');
function key(instance, prop) {
    Tween.get(instance, {override: true}).to({prop: -150}, instance[prop]);
}

Because I need to be able to refer to door['x'] at one point (which is another way of writing door.x), x always need to be a string. However, the same x here needs to be used here as an object property name, but I can't have a string there, because the code would not work:

Tween.get(door, {override: true}).to({'x': -150}, door['x']); // does not work because a string has been passed as an object property name

What I really want is this:

Tween.get(door, {override: true}).to({x: -150}, door['x']); // works

So, my question is: is there some sort of method which allows me to 'unstring' a string? Or is there perhaps any other solution around this?

AKG
  • 2,936
  • 5
  • 27
  • 36
  • Then I'm misunderstanding what's going on then. `{x: -150}` works, but `{'x': 150}` does not. @AlexWayne – AKG Jun 25 '13 at 20:57

1 Answers1

3

Something like this?

function key(instance, prop) {
    var obj = {}; 
    obj[prop] = -150; 
    Tween.get(instance, {override: true}).to(obj, instance[prop]);
}
Brandon Boone
  • 16,281
  • 4
  • 73
  • 100
  • That's a **very** clever way to do that. – AKG Jun 25 '13 at 20:56
  • Object literals may not have dynamic property names. So you have to do it this way. – Alex Wayne Jun 25 '13 at 20:57
  • Thanks @AlexWayne. Still learning :) – AKG Jun 25 '13 at 20:58
  • @AlexWayne What if I now want to use `instance` as a string too (but still keeping it as an object?) Like in `banana['instance']`? I cannot have an object between the brackets. Thanks :) – AKG Jun 25 '13 at 21:24
  • 1
    You cannot get a local variable by a string. But if was assigned to an object, you could fetch it by the property name on that object. `obj.myinstance = instance; var prop = 'myinstance'; obj[prop]` – Alex Wayne Jun 25 '13 at 21:27