'Implicit return in a javascript class method

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?



Solution 1:[1]

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!'))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1