Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

87
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!