Supongamos que tengo este código:
class AuthService { loginWithEmailAndPassword(email, password) { return apolloClient.mutate({}); } } export default new AuthService(); ¿Existe una forma moderna de escribir loginWithEmailAndPassword para tener un retorno implícito?
Sí, con la función de campos de clase pública más reciente, puede agregar la función a su instancia.
class AuthService { loginWithEmailAndPassword = (email, password) => ( { email, password } ) } const authService = new AuthService() console.log(authService.loginWithEmailAndPassword('x@y', 'Password!'))Tenga en cuenta que hay un par de diferencias cuando hace esto:
Un ejemplo del segundo punto:
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. }Si aún no puede usar esta sintaxis, siempre puede crear estas funciones en su constructor, así:
class AuthService { constructor() { this.loginWithEmailAndPassword = (email, password) => ( { email, password } ) } } const authService = new AuthService() console.log(authService.loginWithEmailAndPassword('x@y', 'Password!'))