Javascript MDN 函数原型绑定 polyfill 在数组中是可枚举的
Javascript MDN Function prototype bind polyfill is enumerable in array
我正在做一个项目,在这个项目中,我创建了一个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 上的文档。
相关文章:
- 如何在映射数组中添加换行符
- javascript结合了数组和字典
- 需要帮助设置json数组
- 不能从angular2中的子组件指定父组件中的数组
- 使用JS将数组转换为json对象
- 数组在递归方法中设置为null
- knockoutjs可观察数组
- 如何发送分配列表<字符串>到JavaScript数组或可枚举对象
- JavaScript数组的子类化破坏了快速枚举
- jQuery - 进度条和分页,具体取决于显示的元素和枚举数
- Javascript MDN 函数原型绑定 polyfill 在数组中是可枚举的
- 如何枚举数组的原型
- 不允许枚举跨原点对象-对于对象数组中的(i in x)
- 测试JavaScript关联数组中是否存在枚举值
- 枚举到数组的值
- 从Json文件中加载枚举值数组
- 可枚举属性与数组
- 在javascript中从字符串解析数组的枚举数组
- 用枚举变量填充一个数组
- 灰烬排序一个可枚举数组或添加一个新对象到一个常规数组