Javascript MDN 函数原型绑定 polyfill 在数组中是可枚举的

Javascript MDN Function prototype bind polyfill is enumerable in array

本文关键字:枚举 数组 函数 MDN 原型 绑定 polyfill Javascript      更新时间:2023-09-26

我正在做一个项目,在这个项目中,我创建了一个jQuery插件和其他各种在不同地方使用bind((的js文件。客户端突然请求了 IE8 支持,因此我们包含了一些函数 polyfill 来支持 ie8但在 IE8 中,像下面这样的循环中,方法是可枚举的,这会导致数据损坏。

for (var d in this.originalResponse.timespans) {}

特别是我们的问题是关于 bind((,这是我们正在使用的 mdn polyfill

if (!Function.prototype.bind) {
  Function.prototype.bind = function(oThis) {
    if (typeof this !== 'function') {
      // closest thing possible to the ECMAScript 5
      // internal IsCallable function
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
    }
    var aArgs   = Array.prototype.slice.call(arguments, 1),
        fToBind = this,
        fNOP    = function() {},
        fBound  = function() {
          return fToBind.apply(this instanceof fNOP && oThis
                 ? this
                 : oThis,
                 aArgs.concat(Array.prototype.slice.call(arguments)));
        };
    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();
    return fBound;
  };
}
迭代

的结果将给出一个额外的迭代,其中包含不需要的绑定原型。有没有办法在IE8上支持绑定方法而不枚举?

更新:

this.originalResponse.timespans结构是一个对象,其中键是 unix 时间戳,值是字符串数组。当我尝试循环访问它时,我得到了一个额外的迭代,因为 polyfill(出于我不知道的原因(正在对象内创建一个可枚举的函数原型。

更新 2

数据是从 ajax/JSON 调用接收的,这是来自服务器的示例数据结构:

{  
   "timespans":[  
      {  
         "1417685819":[  
         ]
      },
      {  
         "1417772219":[  
         ]
      },
      {  
         "1417858619":[  
         ]
      }
   ],
   "start":"7:00",
   "current":"11:36",
   "end":"23:00"
}

为了简单起见,在收到这些数据后,我像这样转换数据结构:

MyClass.prototype.success = function( r ) {
    var response = {
        timespans:{}
    };
    response.start = r.start;
    response.end = r.end;
    response.current = r.current;
    for (var t in r.timespans) 
    {
        for (var tt in r.timespans[t])
        {
            response.timespans[tt] = r.timespans[t][tt];
        }
    }  
    var that = this;
    this.originalResponse = response;
    // other code doing some calculation based on this.originalResponse;

 }

如果您支持的旧浏览器不支持Object.defineProperty,那么恐怕这是不可能的。

if (!Function.prototype.bind) {
    Object.defineProperty(Function.prototype, 'bind', {
        value: function() {
            // function body here
        }
    });
}

使用 Object.defineProperty ,默认情况下,属性/方法不可枚举(不会显示在枚举中(、不可配置(无法删除(和不可写(无法覆盖(。

有关更多信息,请参阅 MDN 上的文档