Search code examples
javascriptobjectinstanceloopsfor-in-loop

How to hide properties of an object?


I would like to make some properties of an object to be hidden and some to be visible on iteration. So I tried to use prototype but that's not working:

​function Car(){}

Car.prototype.version = '1.0';

var car_instance = new Car();
car_instance.make = 'BMW';
car_instance.model = 'x5';

for(property in car_instance){
    document.body.innerHTML += property + '<br>';
}

But this outputs version too:

make
model
version

I really like the idea to hide some functions/methods but access it easily like car_instance.version, and in fact if I console.log the object it has other properties too under proto which are not included in the for in loop.

So how should I solve this?


Solution

  • If you want to "hide" a property from a for in loop which is a direct property of the instance, you could use Object.defineProperty:

    Object.defineProperty(car_instance, "version", {
      value: "1.0",
      writable: true,
      configurable: true,
      enumerable: false  // don't make it appear in a for in loop
    });