使用三元运算符声明函数

问题描述 投票:0回答:2

是否可以使用三元运算符来声明函数名?

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);
};
javascript function operators conditional-operator
2个回答
2
投票
this[foo || bar] = function(){alert(true)}

事情是,如果

bar
等于“bar”,你将用一个函数覆盖自己......


0
投票

你真正想要的是这样的东西吗?

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

请注意,“窗口”在某些环境下不可用,尽管所有浏览器都应该有它。

© www.soinside.com 2019 - 2024. All rights reserved.