javascript类方法中的隐式返回



假设我有以下代码:

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

有一个现代的方式来写loginWithEmailAndPassword有一个隐式的回报?

是的,使用较新的公共类字段特性,您可以将该函数添加到实例中。

class AuthService {
loginWithEmailAndPassword = (email, password) => (
{ email, password }
)
}
const authService = new AuthService()
console.log(authService.loginWithEmailAndPassword('x@y', 'Password!'))

注意,当您这样做时,有几个不同之处:

  • 箭头函数自动绑定"this"值,而普通函数不(一般来说,这是一件好事)
  • 这个函数将被添加到实例中,而不是原型中。如果您希望其他人继承您的类,这将产生重要的后果。

第二个点的例子:

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.
}

如果你还不能使用这种语法,你可以在你的构造函数中创建这些函数,像这样:

class AuthService {
constructor() {
this.loginWithEmailAndPassword = (email, password) => (
{ email, password }
)
}
}
const authService = new AuthService()
console.log(authService.loginWithEmailAndPassword('x@y', 'Password!'))