简体   繁体   English

三元运算符的函数声明

[英]Function declaration with ternary operator

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);
};
this[foo || bar] = function(){alert(true)}

问题是,如果bar等于“ bar”,那么您将用一个函数覆盖自己...

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. 请注意,“窗口”在某些环境中不可用,尽管所有浏览器都应具有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM