【问题标题】:Why don't people use Object.defineProperty for polyfills?为什么人们不将 Object.defineProperty 用于 polyfill?
【发布时间】: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…in enumerations are not used arrays :-)

标签: javascript polyfills


【解决方案1】:

主要是因为这些 polyfill 用于 ES5 函数,并且针对没有 Object.defineProperty 的 ES3 环境。

【讨论】:

    猜你喜欢
    • 2015-07-13
    • 2012-10-25
    • 2014-09-20
    • 1970-01-01
    • 2017-02-12
    • 2017-08-14
    • 2019-07-07
    • 1970-01-01
    相关资源
    最近更新 更多