假设我有一个很长的 jquery 方法链,并且想要根据某些 bool 条件添加对两种方法之一的额外调用(例如 show
或 hide
)。
有两种方法:
1) 点符号:将方法链存储在一个变量中,然后调用额外的方法(由if...else
构造解析或三元运算符)与此变量使用点表示法。
代码:
var $tmp = $el._long_()._method_()._chain_();
if (condition) $tmp.show();
else $tmp.hide();
2) 括号表示法:使用方括号表示法追加额外的方法调用(由三元运算符解析)。
代码:
$el._long_()._method_()._chain_()[condition? 'show' : 'hide']();
我过去常常使用第一个,尤其是在别处使用 $tmp
变量时。但第二种方式似乎更简洁,但可读性较差。
对于这种情况,最好的选择是什么?
最佳答案
In JavaScript, one can access properties using the dot notation (foo.bar) or square-bracket notation (foo["bar"]). However, the dot notation is often preferred because it is easier to read, less verbose, and works better with aggressive JavaScript minimizers.
IMO,将三级逻辑放在括号内有点太可爱而且难以阅读。
关于javascript - jquery 方法链中的点与括号表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35949500/