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

131
Visualizações
Can I edit a constructor function in javaScript to add properties?

I have this basic constructor function(with two inputs)

function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; }

To create an object with the constructor function Person, I do

var person1 = new Person("John", "Doe");

the output is

if I want to add a new property to the object person1 (age, for example), I do

person1.age = 20;

and the output is

now, I want to create a new object with the same constructor function... let say person2. Because I know his age, I want to add this info to the object too. I do it like this

var person2 = new Person("Jennifer", "Unknown", 30);

the output is

the output comes without the age property, because the constructor function Person doesn't know it

To create the object person2 with those 3 inputs using Person, I must redefine Person (with those 3 inputs) and recreate person2, passing those 3 info's or add the extra info if object already exists ...

My question is:

How to proceed, if I want to add a third object with Person (person3), by passing 4 inputs (firstName, lastName, age, nationality)? I have to redefine Person (again) and then create person3? ... This seems tedious and not logic work! I confess I'am a newbie in jS!

is it there a way to edit a constructor function without redefining it every time I want to create a new object with extra properties? Can I add new property to a constructor functions without redefining it? And, if I want to edit a constructor function to add a method? for example:

status = function(){
  alert(this.firstName + " " + this. lastName + " " + ", a person with" + " " + this. age + " " + "years old" + " " + "was found nearby doing jS stuff!" )}

summarizing... my goal is:

I start with start and want to end with end without redefining Person, just editing it.

My question make sense? I appreciate any tip.

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

0

Well, there's no such thing as "edit" a function, but you can reuse the old implementation to define your new function instead of rewriting it completely.

function Person(firstName, lastName) {
  this.firstName = firstName
  this.lastName = lastName
}
Person.prototype.speak = function () {
  console.log('hey!')
}

p1 = new Person('first1', 'last1')

console.log('p1 firstName', p1.firstName)
p1.speak() // hey!

// store old prototype object
oldPrototype = Person.prototype


Person = function (firstName, lastName, age) {
  // call the old constructor to initialize with existing properties
  oldPrototype.constructor.call(this, firstName, lastName)

  // assign new properties
  this.age = age
  // assign a new default property
  this.otherProp = 'new prop'
}

// copy over the old prototype to the new Person
Person.prototype = oldPrototype

p2 = new Person('first2', 'last2', 10)

console.log('p2 firstName', p2.firstName)
console.log('p2 new properties', p2.age, p2.otherProp) // 10 and 'new prop'

p2.speak() // should work! because we already copied the old prototype object over

// it will not affect any of the old Person instances that were initialized before
console.log('p1 age', p1.age) // undefined
console.log('p1 otherProp', p1.otherProp) // undefined

While this is possible, don't overuse it!

Because it seems like an anti-pattern to override a constructor function. You should better create a new constructor function by extending your Person instead.

Read more about Inheritance in JavaScript

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