-1

I am wondering whether I can use variables that I pass to a function as arguments as "literals" (I don't know a better way to describe the problem, perhaps the example will clear things up):

banana = yellow;
minion = cute;

function ex(banana, minion) {
    banana.minion;
}

// What I want is: yellow.cute

Edit I think I might not have been asking exactly what I meant. I'm sorry for that. Here's the actual code that might clarify things.

function ex(banana, minion){
    createjs.Tween.get(banana, {override: true}).to({banana: minion}, -(value + -banana.minion) * speed, createjs.Ease.ease);
console.log(banana); // returns 'yellow'
console.log(minion); // returns 'cute'
console.log(banana.minion); // returns 'undefined'
console.log(banana[minion]); // returns 'undefined' too
}

So I want to pass whatever I define as banana or minion to be 'literal', so that it will read createjs.Tween.get(yellow, {override: true}).to({yellow: cute}, -(value + -yellow.cute) * speed, createjs.Ease.ease);

AKG
  • 2,936
  • 5
  • 27
  • 36

2 Answers2

2

You can pass the name as a string and use the array syntax to access the property.

function ex(banana, minion) {
  return banana[minion];
}

If you want the left hand side of an object to be a string as well (e.g. banana, you could use eval(banana)[minion] but that might raise a few eyebrows at a code review. Note that this works for both properties and methods e.g. eval(banana)[minion](), though I'd step back a bit and ask why you need to do this kind of moderately bonkers stuff :)

Jeff Foster
  • 43,770
  • 11
  • 86
  • 103
  • Sorry, I wasn't clearer. `minion` is supposed to reference to a method. So the function will pass whatever name I pass to `minion` as the method for `banana`. Hope this makes more sense. – AKG Jun 24 '13 at 08:59
  • 1
    @AKG: Method or property, it doesn't matter. You can use the same idea for methods. – Jakob Jun 24 '13 at 09:03
  • Please see updated question. Sorry for the confusion. – AKG Jun 24 '13 at 09:07
1

Use bracket notation instead of dot notation as the member operator

ex

 banana[minion];
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531