javascript - 为什么人们不使用 Object.defineProperty 作为 polyfill?

标签 javascript polyfills

例如,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/

相关文章:

javascript - 无法从巨大的 xlsx 文件中获取正确的表格 - 使用 NodeJS XLSX 库

javascript - 如何在 jQuery DataTable 中绘制 Excel 样式的数据条?

javascript - ng-click 不自动更新 UI

带有 location.href 的 Javascript 定时弹出警报

javascript - 我可以在不破坏新浏览器的情况下使用 "one fits all"polyfill 集合吗?

javascript - css3-mediaqueries.js VS respond.js

jquery - CSS3 动画填充模式 polyfill

javascript - Onclick 粗体选择

angular - 在 Internet Explorer 11 中使用 Angular Elements 的推荐方法

javascript - Shim 与 Sham : What is the difference?