问题描述
ES5有一个可枚举的标志。
ES5 has a enumerable flag. Example
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor
, pd = getOwnPropertyDescriptor(Object.prototype, "toString");
assert(pd.enumerable === false, "enumerability has the wrong value");
部分实施
可以通过 Object.keys
和对象来实现.getOwnPropertyNames
使用shimmed Object.defineProperty
过滤掉新的非可枚举属性。
Partial implementation
Partial implementation is do-able by having Object.keys
and Object.getOwnPropertyNames
filter out new non-enumerable properties using the shimmed Object.defineProperty
.
这允许属性不可枚举。这显然意味着
This allows for properties to be non enumerable. This clearly means that Example
for (var key in {}) {
assert(key !== "toString", "I should never print");
}
这允许我们添加属性来说对象。原型
()
This allows us to add properties to say 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兼容的浏览器中模拟这一点?
Question
How can we emulate this in non-ES5 compliant browsers?
在这种情况下,我们关心可能解决此问题
In this case we care about potentially solving this for
- IE< 9(IE8仅适用于DOM对象)
- Firefox 3.6
- Safari 4
- Opera 11.5(Opera 11.6解决了这个问题。)。
- IE < 9 (IE8 only works on DOM objects)
- Firefox 3.6
- Safari 4
- Opera 11.5 (Opera 11.6 solves this).
没有解决方案。
ES5垫片有,如果它不起作用。
The ES5 shim has a solution for most ES5 features that will break your code if it doesn't work.
是否有任何黑魔法这可以通过仅限固定IE的API来完成吗?也许使用VBScript?
Is there any black magic that can be done with propiotory IE only APIs? Maybe with VBScript?
推荐答案
您可以通过代码重写来实现。将的每次使用改为(p in o)body
改为
You can do it via code-rewriting. Rewrite every use of for (p in o) body
to
for (p in o) {
if (!(/^__notenum_/.test(p) || o['__notenum_' + p])) {
body
}
}
然后你可以通过定义 __ notenum_来标记不可枚举的属性。 。
属性。为了兼容,你必须调整上面的内容,以确保 __ notenum_propname
定义在与 propname
相同的原型级别,如果您使用它们,请覆盖 eval
和新函数
进行重写。
and then you can mark properties not enumerable by defining a __notenum_...
property. To be compatible you would have to tweak the above to make sure that __notenum_propname
is defined at the same prototype level as propname
, and if you use them, overwrite eval
and new Function
to rewrite.
这基本上是所做的。
这篇关于是否可以模拟不可枚举的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!