简体   繁体   English

如何使用三元运算符来选择函数

[英]How to use ternary operator to select function

The following snippet works 以下代码段有效

if (condition)
  node.addClass('myclass');
else
  node.removeClass('myclass');

but not this one 但不是这个

node[condition ? 'addClass' : 'removeClass']('myclass');

nor this one 也不是这个

(condition ? node.addClass : node.removeClass)('myclass');

If I test it with 如果我测试它

console.log(node[condition ? 'addClass' : 'removeClass']);

the browser prints that it's a function. 浏览器打印出它是一个功能。 Why can't I call it? 为什么我不能打电话给它?

It apparently works the way I gave my examples here. 它显然与我在这里给出的例子一样。 It doesn't work with one extra level of indirection. 它不适用于一个额外的间接级别。

function print(x) {
  console.log(x);
  return x;
}

print(condition ? node.addClass : node.removeClass)('myclass');

With this code, Chrome tells me this: 使用此代码,Chrome会告诉我:

Uncaught TypeError: Cannot read property '0' of undefined 未捕获的TypeError:无法读取未定义的属性“0”

But I found out I can circumvent the problem by using call to pass the node as this to the function. 但是我发现我可以使用绕过这个问题call到传递node作为this的功能。

print(condition ? node.addClass : node.removeClass).call(node,'myclass');

Obviously, the right solution in this specific case is to use toggleClass , as @epascarello pointed out. 显然,在这种特定情况下,正确的解决方案是使用toggleClass ,正如@epascarello指出的那样。 I'm a little surprised that this gets lost in this scenario. 我有点意外,在这种情况下, this会丢失。

可以用vanilla java脚本切换

node.classList.toggle('myclass',condition);

You can do this by assigning the function to a variable. 您可以通过将函数分配给变量来完成此操作。

 var twoLevel = { "foo" : { log: console.log }, "bar" : { log: window.alert } } var fn = true ? twoLevel["foo"].log : twoLevel["bar"].log; fn('test') 

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

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