例如,Mozilla 开发者网络仅使用 Array.prototype = function 来定义 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;
}
});
最佳答案
主要是因为这些polyfills是针对ES5函数的,并且目标是没有Object.defineProperty
的ES3环境。
关于javascript - 为什么人们不使用 Object.defineProperty 作为 polyfill?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45744562/