tags:

views:

65

answers:

3

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?

+1  A: 

Nope, not possible. You can hide things by using closures though.

Matti Virkkunen
Hide... *things*? Ok, what was the question again, hmmm... :)
npup
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
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
not possible then afaik, even with visual studio / .net reflection private properties are visible in the debug information.
James Westgate
@James: JavaScript is not .NET.
Matti Virkkunen
@Matti - yeah no kidding. I was just saying that in other languages the private properties are enumerable at runtime.
James Westgate
+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
+1 - `defineProperty` is almost supported in IE8, the almost meaning that it's on DOM objects only. http://msdn.microsoft.com/en-us/library/dd548687(VS.85).aspx
Andy E
Andy: thanks, that's interesting. I hadn't looked up what the "almost" meant.
Tim Down