0

Is it possible to use a ternary operator to declare the function name?

var foo,
    bar = 'bar';

(foo || bar) = function(){ // Invalid left-hand side in assignment [Bad assignment]
    alert(true);
};

[foo || bar] = function(){ // Invalid left-hand side in assignment [Bad assignment]
    alert(true);
};

(foo ? foo : bar) = function(){ // Invalid left-hand side in assignment [Bad assignment]
    alert(true);
};
yckart
  • 32,460
  • 9
  • 122
  • 129

2 Answers2

2
this[foo || bar] = function(){alert(true)}

Thing is, if bar equals "bar", you're going to overwrite yourself with a function...

lc.
  • 113,939
  • 20
  • 158
  • 187
  • Ok, works in my case as described above, however not in my real world example: http://jsfiddle.net/ARTsinn/2pk9y/5/ – yckart Jan 24 '13 at 07:06
0

What you really want is something like this?

window[foo ? foo : bar] = function (){
    alert(true);
};

Please note that "window" is not available in some environment, though all the browsers should have it.

Dukeland
  • 146
  • 4
  • Ok, works in my case as described above, however not in my real world example: http://jsfiddle.net/ARTsinn/2pk9y/5/ – yckart Jan 24 '13 at 07:06
  • 1
    alert(typeof $.fx.step._default); alert(typeof $.Tween.propHooks._default.set); Adding these 2 lines in your code may help you understand it. One is "undefined" and the other one is "function". Of course you cannot use them to name your function. – Dukeland Jan 24 '13 at 07:13