1

Suppose I have this code:

class AuthService {
  loginWithEmailAndPassword(email, password) {
    return apolloClient.mutate({});
  }
}

export default new AuthService();

is there a modern way to write loginWithEmailAndPassword to have an implicit return?

1
  • 1
    You can use an arrow function. Commented Aug 26, 2021 at 0:24

1 Answer 1

3

Yes, using the newer public class fields feature, you can add the function to your instance.

class AuthService {
  loginWithEmailAndPassword = (email, password) => (
    { email, password }
  )
}

const authService = new AuthService()
console.log(authService.loginWithEmailAndPassword('x@y', 'Password!'))

Note that there's a couple differences when you do this:

  • Arrow functions automatically bind the "this" value whereas normal functions do not (in general, this is a good thing anyways)
  • This function will be added onto the instance, not the prototype. This has important consequences if you expect others to be inheriting your class.

An example of the second point:

class BaseClass {
  f = () => 2
}

class SubClass extends BaseClass {
  f() {} // Doesn't work - this won't shadow f() from the parent class
  f = () => super.f() // Doesn't work. This overrides f() from the parent class, so you can't access it's super method.
}

If you're not yet able to use this syntax, you can always create these functions in your constructor, like this:

class AuthService {
  constructor() {
    this.loginWithEmailAndPassword = (email, password) => (
      { email, password }
    )
  }
}

const authService = new AuthService()
console.log(authService.loginWithEmailAndPassword('x@y', 'Password!'))

Sign up to request clarification or add additional context in comments.

4 Comments

apolloClient.mutate returns a promise, I'm getting errors with this syntax, that's also why I'm asking
It should work, even if it returns a promise. This syntax is fairly new, so you need to make sure your platform supports it, otherwise, you would get a syntax error. You can check the browser compatibility table at the bottom of this page: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
why are you using { email, password } as return value? it is destructuring or a weird object?
{ email, password } is just shorthand for { email: email, password: password }, i.e. I was just making the dummy function return an object that contained the parameters that were passed in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.