【发布时间】:2013-06-20 08:39:40
【问题描述】:
我一直在浏览 Mozilla 开发者网络 (MDN) 上的 polyfill 实现,因为我需要其中一些作为库。 我知道 shim.js 存在,但我没有使用它。
似乎 polyfill 在代码样式上并不一致。看起来它们几乎是由社区以几乎“维基”的风格编写的。
以String.prototype.contains为例
if(!('contains' in String.prototype)) {
String.prototype.contains = function(str, startIndex) {
return -1 !== String.prototype.indexOf.call(this, str, startIndex);
}
}
这样实现对我来说似乎更合乎逻辑:
if(!String.prototype.contains) {
String.prototype.contains = function(str, startIndex) {
return this.indexOf(str, startIndex) !== -1;
}
}
鉴于 JavaScript 是一种对大小至关重要的语言(因为对于网络传输,一切都应该尽可能小),我的示例应该对 MDN 上的示例有利,因为这样可以节省一些字节。
正如标题所示,我想知道代码在 MDN 上的可靠性如何,我是否应该根据需要对其进行修改以尽可能提供真正干净、微小的实现?
【问题讨论】:
标签: javascript mozilla polyfills shim