JS ECMA6 - 用于向后兼容的三元运算符

JS ECMA6 - Ternary Operator for backwards compatibility

我有一段 javascript 代码使用 ECMA6 数据集 属性 访问元素 e 的对象 data-foo 属性。不幸的是,这与 <=IE10 不兼容。为了解决这个问题,我将我的代码重写为使用三元运算符,在支持时使用数据集,在不支持时使用 getAttribute:

(e.dataset) ? e.dataset.foo : e.getAttribute('data-foo');

但我为什么不直接用 e.getAttribute('data-foo') 替换整行呢?当以前的标准一样好并且得到更广泛的支持时,使用 ECMA6 标准的真正好处是什么?

首先,dataset 属性 似乎不是 ES6 规范的一部分。它是 HTML spec.

的一部分

回答你的问题,

What is the real benefit of using ECMA6 standards when previous standards are just as good and more widely supported?

简单。

如您所见,在 e.dataset.fooe.getAttribute('data-foo') 这两种方法中,前者的冗长程度较低,因此在许多情况下是可取的。一方面,它减少了您发送的 Javascript 文件的大小。

规范甚至强调了这一点:

The dataset IDL attribute provides convenient accessors for all the data-* attributes on an element. ...

[Emphasis mine]