0

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

1 Answers1

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320