Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

95
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda