jQuery方法链接中的点对括号表示法 [英] dot vs bracket notation in jquery method chaining

查看:118
本文介绍了jQuery方法链接中的点对括号表示法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一长串的jquery方法,并且想根据某些布尔条件添加两个方法之一(例如showhide)的额外调用.

Suppose that I have a long chain of jquery methods and want to add extra call of one of two methods (e.g. show or hide) depending on some boolean condition.

有两种方法可以做到:

1) 点符号 :将方法链存储在变量中,然后使用该变量使用点调用额外的方法(由构造或三元运算符解析)符号.

1) Dot notation: store the method chain in a variable, then call extra method (resolved by if...else construct or ternary operator) with this variable using dot notation.

代码:

var $tmp = $el._long_()._method_()._chain_();
if (condition) $tmp.show();
else $tmp.hide();

2) 括号符号 :使用方括号符号附加方法的额外调用(由三元运算符解析).

2) Bracket notation: append extra call of method (resolved by ternary operator) using square bracket notation.

代码:

$el._long_()._method_()._chain_()[condition? 'show' : 'hide']();

我曾经使用第一个,尤其是在其他地方使用$tmp变量的情况下.但是第二种方法似乎更简洁,但可读性较差.

I used to use the first one, especially if $tmp variable is used elsewhere. But the second way seems to be more concise though less readable.

在这种情况下,最佳选择是什么?

What would be the best choice for such case?

推荐答案

eslint 喜欢

在JavaScript中,人们可以使用点符号来访问属性 (foo.bar)或方括号表示法(foo ["bar"]). 但是,点 记法通常是首选,因为它更易于阅读,更少 冗长,并且可以与积极的JavaScript最小化器一起更好地工作.

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,将三级逻辑放在方括号内有点太可爱了,很难阅读.

IMO, putting tertiary logic inside of bracket's is a little too cute and hard to read.

这篇关于jQuery方法链接中的点对括号表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆