Objects with For / In

2
  

I have a function added in a prototype, and I do not want it   is listed in a for / in loop but rather executed, but when calling   console, in the for / in loop it is displayed and not executed, so I created   a case "if" to read the object's data to be a function   perform the function (worked). But how can I hide the   function on the console? I want it to be read when it is read.   execute, how can I do this with a for / in loop?

Instead of displaying on the console the section "function () {console.log ('vrum vrum');}" - I wanted to hide it and display what was defined in the function - the "vrum vrum" .. the question became confusing .. was it bad!?

function CarroAspects(modelo, chassi, qtdPortas){
    this.modelo = modelo;
    this.chassi = chassi;
    this.qtdPortas = qtdPortas;
}
CarroAspects.prototype.andar = function(){
    console.log('vrum vrum');
}
const carroPrototipo = new CarroAspects('protótipo', '1290381209', 2);
for(var carroProperty in carroPrototipo){
    console.log(carroPrototipo[carroProperty]); // console -> listará Propriedades do Objeto
    if(typeof carroPrototipo[carroProperty] === 'function'){ // Executará a função
        carroPrototipo[carroProperty]();
    }
}
    
asked by anonymous 13.06.2018 / 20:49

1 answer

3

You can use Object.defineProperty() with enumerable: false, , and this will hide ownership of iterators.

function CarroAspects(modelo, chassi, qtdPortas) {
  this.modelo = modelo;
  this.chassi = chassi;
  this.qtdPortas = qtdPortas;
}
Object.defineProperty(CarroAspects.prototype, 'andar', {
  enumerable: false,
  configurable: false,
  writable: false,
  value: function() {
    console.log('vrum vrum');
  }
});
const carroPrototipo = new CarroAspects('protótipo', '1290381209', 2);
for (var carroProperty in carroPrototipo) {
  console.log(typeof carroPrototipo[carroProperty]); // var dar: string, string, number Objeto
}

console.log('Vamos dar uma volta?');
carroPrototipo.andar(); // vai dar : vrum vrum

Edit after the edit in question:

If I understood correctly you should use getter to do what you want. Again using the same technique ( Object.defineProperty ), but with a variant:

function CarroAspects(modelo, chassi, qtdPortas) {
  this.modelo = modelo;
  this.chassi = chassi;
  this.qtdPortas = qtdPortas;
}

function vrumVrum() {
  return 'vrum vrum';
}
Object.defineProperty(CarroAspects.prototype, 'andar', {
  enumerable: true,
  get() {
    return vrumVrum();
  }
});
const carroPrototipo = new CarroAspects('protótipo', '1290381209', 2);
for (var carroProperty in carroPrototipo) {
  console.log(carroPrototipo[carroProperty]); // var dar: protótipo, 1290381209, 2, vrum vrum
}
    
13.06.2018 / 20:53