Reputation: 16491
I have a class that performs a login request on instantiation, I only want this login request to be performed by the base class and for all other instances to acknowledge that the login has been performed. Can anyone recommend how this can be achieved, would this be a use-case for making the login function static?
// Example
class Content {
constructor() {
this.performLogin()
}
performLogin() { // will making this static achieve my request?
// go fetch if 1st time
// else bypass this step
}
performLogout() {
// perform log out once only
}
}
class ContentOne extends Content {
constructor() {
super()
}
doSomethingElse() {
//...
}
}
class ContentTwo extends Content {
constructor() {
super()
}
alertUser() {
//...
}
}
const contentOne = new ContentOne()
const contentTwo = new ContentTwo()
Upvotes: 0
Views: 41
Reputation: 190945
A better design would be to have a LoginService
that would manage that. If already logged in, it would just ignore the request. For example,
class LoginService {
constructor() {
this.isLoggedIn = false;
}
login() {
if (this.isLoggedIn) { return; }
// do work
this.isLoggedIn = true;
}
}
class Content {
constructor(loginService) {
this.loginService = loginService;
this.performLogin()
}
performLogin() {
this.loginService.login();
}
performLogout() {
// perform log out once only
}
}
const loginService = new LoginService();
const contentOne = new ContentOne(loginService);
const contentTwo = new ContentTwo(loginService);
Making a function static
won't prevent something being called more than once.
Upvotes: 2