【发布时间】:2018-01-26 10:14:34
【问题描述】:
例如,Mozilla 开发者网络简单地使用 Array.prototype = 函数来定义 polyfill,但这会创建一个中断 for-in 循环的可枚举属性。
所以我使用了 Object.defineProperty(Array.prototype, { enumerable: false ...
这有什么危险吗?为什么这不是常见的方式?
这是一个来自 MDN 的示例 polyfill: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Polyfill
这是与 defineProperty 相同的示例:
Object.defineProperty(Array.prototype, {
enumerable: false,
value: function(func, thisArg) {
'use strict';
if ( ! ((typeof func === 'Function') && this) )
throw new TypeError();
var len = this.length >>> 0,
res = new Array(len), // preallocate array
c = 0, i = -1;
if (thisArg === undefined)
while (++i !== len)
// checks to see if the key was set
if (i in this)
if (func(t[i], i, t))
res[c++] = t[i];
else
while (++i !== len)
// checks to see if the key was set
if (i in this)
if (func.call(thisArg, t[i], i, t))
res[c++] = t[i];
res.length = c; // shrink down array to proper size
return res;
}
});
【问题讨论】:
-
链接到示例 polyfill?
-
感谢您的建议。
-
给出的例子与
defineProperty的版本相同。用另一个填充一个看起来很奇怪。 -
"一个打破 for-in 循环的可枚举属性" - 不是真的,当
for…inenumerations are not used arrays :-)
标签: javascript polyfills