Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
78
rated 0 times [  79] [ 1]  / answers: 1 / hits: 31504  / 14 Years ago, wed, april 14, 2010, 12:00:00

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?


More From » javascript

 Answers
2

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 log name=>Fred */
for (var i in obj) {
console.log(i + => + obj[i]);
}


This works in current browsers: see http://kangax.github.com/es5-compat-table/ for details of compatibility in older browsers.



Note that the property must also be set writable in the call to Object.defineProperty to allow normal assignments (it's false by default).


[#97077] Monday, April 12, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
joanneamiyaa

Total Points: 532
Total Questions: 127
Total Answers: 98

Location: Guam
Member since Tue, Nov 3, 2020
4 Years ago
;