问题描述
我想创建一个具有隐藏属性的对象(一个不会出现在中的属性(obj
循环中的var x)。是否可以执行这个?
I want to create an object with a hidden property(a property that does not show up in a for (var x in obj
loop). Is it possible to do this?
推荐答案
在ECMAScript 3中是不可能的(这个问题被问到时主流浏览器实现的是什么但是,在ECMAScript 5中,所有主要浏览器的当前版本都实现了,可以将属性设置为不可枚举:
It isn't possible in ECMAScript 3 (which was what the major browsers implemented at the time this question was asked in 2010). However, in ECMAScript 5, which current versions of all major browsers implement, it is possible to set a property as non-enumerable:
var obj = {
name: "Fred"
};
Object.defineProperty(obj, "age", {
enumerable: false,
writable: true
});
obj.age = 75;
/* The following will only alert "name=>Fred" */
for (var i in obj) {
window.alert(i + "=>" + obj[i]);
}
这适用于当前浏览器:参见 f或旧版浏览器兼容性的详细信息。
This works in current browsers: see http://kangax.github.com/es5-compat-table/ for details of compatibility in older browsers.
请注意,在调用允许正常分配(默认情况下它是 false
。
这篇关于是否可以在javascript中创建隐藏属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!