Doubt with exercise of Ecmascript 6

Asked

Viewed 50 times

0

This Ecmascript exercise talks about the creation of two classes, one of user (where the email and password will be entered), the other of administrator (where in addition to the email and password entry, it speaks if it is Adm.

Why the input method isAdmin() is in the user class and not the administrator? I mean, if it’s to verify that the class is an administrator, wouldn’t it be better to stay in the administrator class?

The code in question is this:

class Usuario{
    constructor(email, senha){
        this.email = email;
        this.senha = senha;
    }
    isAdmin(){
        return this.admin === true;
    }
}

class Admin extends Usuario{
    constructor(email, senha){
        super(email, senha);

        this.admin = true;
    }
}

const User1 = new Usuario("[email protected]", "senha123");
const Adm1 = new Admin("[email protected]", "senha123");

console.log(User1.isAdmin()); //retornará false
console.log(Adm1.isAdmin());  //retornará true

  • 3

    How would you test whether an ordinary user is an administrator if the method isAdmin were only in Admin?

  • 4

    Is this some course exercise? Course exchange, one that teaches to do wrong is not a good one. @Luizfelipe is right, the mistake is to have inheritance. And that should be clear, because if the inheritance made sense, you wouldn’t need to check that that’s what you say it is.

  • 2

    To complement the comment by @Maniero, you have a question about It is wrong to use class inheritance to group common behaviors and attributes?

  • 2

    Perhaps it is the case to show the problems of a solution before showing a better way. The only way to know is to see the next classes of the course or ask who did it.

1 answer

-1

The Admin class inherits the methods and attributes of the user class, so extends it. Think that an admin is a user, and he needs to check if the user is an Admin, and not if an Admin is an Admin. I hope to have helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.