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

89
Visualizações
Proper way to inherit an object constructor's prototype?

In the following code, which is the correct way to inherit an object constructor's prototype? I want Admin's prototype to have the 'login' method that was previously attached to the User prototype. I've tried both and I'm not exactly sure which is the correct way.

function User(email, name) {
    this.email = email;
    this.name = name;
    this.online = false;
}

User.prototype.login = function() {
    this.online = true;
    console.log(this.email, 'has logged in');
}

function Admin(...args) {
    User.apply(this, args);
    this.role = 'super admin';
}

Admin.prototype = Object.create(User.prototype);  //option 1
Admin.prototype = User.prototype;                 //option 2
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Option 1 is definitely the better approach, because it creates a new object that inherits from but is not the same as User.prototype.

Option 2 means that any changes to Admin.prototype will be exactly reflected on User.prototype, which is not desirable; with that approach, they're the exact same object.

Demo:

function User(email, name) {
    this.email = email;
    this.name = name;
    this.online = false;
}

User.prototype.login = function() {
    this.online = true;
    console.log(this.email, 'has logged in');
}

function Admin(...args) {
    User.apply(this, args);
    this.role = 'super admin';
}

Admin.prototype = User.prototype;                 //option 2

Admin.prototype.getAdminInfo = function() {
  console.log('getting admin info');
}
const user = new User('useremail');
user.getAdminInfo();

You should use Admin.prototype = Object.create(User.prototype); instead. This way, methods on User become available on Admin, but you'll be able to create separate Admin-only methods as well without changing User.

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