简体   繁体   English

在方括号中使用classList方法

[英]Using classList method in square brackets

Is the putting a classList method inside square brackets considered as good practice? 将classList方法放在方括号内是否被认为是一种好习惯? I mean, sometimes I prefer to do: 我的意思是,有时候我更喜欢这样做:

elem.classList[ifTrue ? 'add' : 'remove']('className');

as opposed to: 相对于:

if (ifTrue) {
    elem.classList.add('className');
} else {
    elem.classList.remove('className');
}

Also, does using brackets have any impact on the performance/speed of code execution? 另外,使用方括号是否会对代码执行的性能/速度产生影响?

Is the putting a classList method inside square brackets considered as good practice? 将classList方法放在方括号内是否被认为是一种好习惯?

There's nothing really wrong with it. 没什么错。 It's shorter, more concise, no code duplication. 它更短,更简洁,没有代码重复。 As you say, you sometimes prefer it - if you know when to use and when not, then it's fine. 如您所说, 有时更喜欢它-如果您知道何时使用和何时不使用,那就很好。 The factors are: 这些因素是:

  • readability . 可读性 Much opinion-based. 很多基于意见的。 I like it, others don't. 我喜欢,其他人不喜欢。 Know your audience, I wouldn't suggest this for newbies. 了解您的观众,我不会建议新手使用。
  • maintainability . 可维护性 When it's likely that other things need to be done depending on ifTrue , then I'd choose if-else. 当可能需要根据ifTrue完成其他事情时,我将选择if-else。 On the other hand, the repetion of elem.classlist and 'classname' are not optimal either. 另一方面, elem.classlist'classname'elem.classlist也不是最优的。
  • performance . 表现 The second is more likely to be optimised (because static method names), that's true. 第二个更有可能被优化(因为静态方法名称),这是事实。 But there hardly is measurable impact on your execution speed, as the most significant work is done in the DOM. 但是,由于最重要的工作是在DOM中完成的,因此对您的执行速度几乎没有可衡量的影响 You're not using this piece of code in a performance-critical section anyway. 无论如何,您不会在性能至关重要的部分中使用这段代码。 (Do you? Then benchmark). (是吗?然后进行基准测试)。

There is a completely different and much better third way though: Using the toggle method of classlists . 但是,还有一种完全不同且更好的第三种方法:使用classliststoggle方法 It does take a second parameter which does just what you want to do: 它确实需要第二个参数,它可以完成您想做的事情:

elem.classList.toggle('className', ifTrue);

It was just invented for this very common case! 它是为这种非常常见的情况而发明的! Admittedly, it's worse for readability as many developers don't know what toggle does. 诚然,由于许多开发人员不知道toggle是什么,因此可读性更差。

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

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