【发布时间】:2012-02-13 15:19:21
【问题描述】:
ES5 有一个可枚举的标志。 Example
示例
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor
, pd = getOwnPropertyDescriptor(Object.prototype, "toString");
assert(pd.enumerable === false, "enumerability has the wrong value");
部分实现
Partial implementation 可以通过 Object.keys 和 Object.getOwnPropertyNames 使用填充的 Object.defineProperty 过滤掉新的不可枚举属性来实现。
简介
这允许属性不可枚举。这显然意味着Example
for (var key in {}) {
assert(key !== "toString", "I should never print");
}
这允许我们添加属性说Object.prototype (Example)
Object.defineProperty(Object.prototype, "toUpperCaseString", {
value: function toUpperCaseString() {
return this.toString().toUpperCase();
},
enumerable: false
});
for (var key in {}) {
assert(key !== "toUpperCaseString", "I should never print");
}
console.log(({}).toUpperCaseString()); // "[OBJECT OBJECT]"
问题
我们如何在不符合 ES5 的浏览器中模拟这一点?
在这种情况下,我们关心的是潜在地解决这个问题
- IE
- 火狐3.6
- Safari 4
- Opera 11.5(Opera 11.6 解决了这个问题)。
ES5-shim 对此没有解决方案。
如果 ES5 shim 不起作用,它会有一个 solution for most ES5 features that will break your code。
有没有什么黑魔法可以用专有的 IE 专用 API 来完成?也许用 VBScript?
【问题讨论】:
-
shim 可能永远无法实现这一点,因为
for... in的行为被硬连线到语言规范和解释器中。您要求的是不符合 ES5 的浏览器中不存在的东西。 +1 不过,您的问题总是很有趣。 -
@FrédéricHamidi 在看到上面链接的 VB 黑魔法之后,我不再那么确定了。
-
@FrédéricHamidi 我的知识说“这不可能”,但浏览器有很多奇怪的专有 API,这可能是可能的
-
你试过traceur吗? code.google.com/p/traceur-compiler
-
@Tom traceur 如何提供帮助?我不知道怎么做。
标签: javascript internet-explorer ecmascript-5 emulation