Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
How does one correctly implement a constructor function's instance methods?

Following constructor function and log code is given ...

function Car(brand, year, model, color, utilidad) {
  this.brand = brand;
  this.year = year;
  this.model = model;
  this.color = color;
  this.utilidad = utilidad;
  this.useFor = (prmt) => {
    this.utilidad.push(prmt);
  }
};

const toyota = new Car("Toyota", 2021, "Prado", "Red", "city");
toyota.useFor('mountain');

console.log(toyota);

Instead of getting the expected log data the code breaks with following message ...

TypeError: "this.utilidad.push is not a function"

Why does this happen?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

because *.push() use to insert data in array, but you put string "city" on default parameter;

about 4 years ago · Juan Pablo Isaza Relatório

0

From the above comment ...

"The OP did not build a prototype but was implementing a function which is intended to be used as constructor in order to create Car instances. On top the OP is initializing toyota with a wrongly typed utilidad argument which is supposed to be an array and not a string in oder to allow the useFor method to later push into the object's own utilidad property."

Thus a refactored Car implementation internally might use initial or default values for omitted argument values. It might introduce some formal type checking in order to not break from TypeErrors due to wrongly provided argument types. And in addition to the tasks of assigning the arguments as own properties to an object it does implement its only method at the constructor function's prototype ...

function Car(
  brand = 'unknown',
  year = 'not provided',
  model =  'unknown',
  color = 'not provided',
  utilidad = [],
) {
  return Object.assign(this, {
    brand,
    year,
    model,
    color,
    utilidad: Array.isArray(utilidad)
     ? utilidad
     : [utilidad],
  });
};
Car.prototype.useFor = function useFor (value) {
  this.utilidad.push(value);
};


const dummy = new Car();
const toyota = new Car('Toyota', 2021, 'Prado', 'Red', 'city');

dummy.useFor('test field');
toyota.useFor('mountain');

console.log({ dummy, toyota });
.as-console-wrapper { min-height: 100%!important; top: 0; }

The next iteration might introduce class syntax and a constructor which expects a single config or options argument ...

class Car {
  constructor({
    brand = 'unknown',
    year = 'not provided',
    model =  'unknown',
    color = 'not provided',
    utilidad = [],
  }) {
    Object.assign(this, {
      brand,
      year,
      model,
      color,
      utilidad: Array.isArray(utilidad)
       ? utilidad
       : [utilidad],
    });
  }
  // prototype method(s)
  useFor(value) {
    this.utilidad.push(value);
  }
}


const dummy = new Car({});
const toyota = new Car({
  brand: 'Toyota',
  year: 2021,
  model: 'Prado',
  color: 'Red',
  utilidad: 'city',
});

dummy.useFor('test field');
toyota.useFor('mountain');

console.log({ dummy, toyota });
.as-console-wrapper { min-height: 100%!important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda