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 - Angular - protected 页面

javascript - TextDecoder 的 Polyfill

CSS4 Grid-Structural 伪类 polyfill ( :nth-column)

javascript - Angular 5 (IE11) 错误 : Uncaught (in promise): Error: Cannot match any routes

javascript - 当我的应用程序包含查询字符串时,如何使用 OneDrive Web 选择器

javascript - 五指 : command to search BTDIGG. 组织

javascript - 无法使用 API 从 Google 云端硬盘下载文件 - node.js

javascript - Angular2 HTTP : Uncaught SyntaxError: Unexpected token < polyfills

javascript - Temasys 如何更改现有代码

javascript - 如何在 jquery javascript 中从 localstorage 保存和获取表单状态