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?
views:
65answers:
3
+1
A:
Nope, not possible. You can hide things by using closures though.
Matti Virkkunen
2010-04-14 10:15:56
Hide... *things*? Ok, what was the question again, hmmm... :)
npup
2010-04-14 20:28:53
A:
I think this is possible as long as the loop is not recursive (sort of inspired by Matti's answer above)
Consider this example.
var obj = {
name: 'jim',
age: '35',
hidden: {status: 'cool'}
}
Your code above will produce the following output
jim
35
(object)
James Westgate
2010-04-14 10:20:38
I want the hidden property not to be iterated over i.e. in this example for only 2 of the properties to show up
tmim
2010-04-14 10:45:23
not possible then afaik, even with visual studio / .net reflection private properties are visible in the debug information.
James Westgate
2010-04-14 10:50:36
@Matti - yeah no kidding. I was just saying that in other languages the private properties are enumerable at runtime.
James Westgate
2010-04-14 12:27:56
+3
A:
It isn't possible in ECMAScript 3 implementations (which covers all the current major browsers). However, in ECMAScript 5 which will be implemented in browsers soon, it is possible to set a property as non-enumerable:
var obj = {
name: "Fred"
};
Object.defineProperty(obj, "age", {
enumerable: false
});
obj.age = 75;
/* The following will only alert "name=>Fred" */
for (var i in obj) {
window.alert(i + "=>" + obj[i]);
}
This does work in some current and imminent browsers: see http://kangax.github.com/es5-compat-table/ for details.
Tim Down
2010-04-14 10:53:13