如何解决javascript类中的静态异步函数
我在使用 javascript 类上的静态异步方法时遇到问题。 如果我删除 static 关键字,它可以在类中正常调用,但我将无法使用类调用它。
我想要的结果是使用 User.exist(email) 在类 itselt 和类 ex 的实例上使用exist方法。 foo.exist(email)
我认为哪里错了?
const userEmails = []
class User {
constructor(fields) {
this.email = fields.email;
this.name = fields.name;
}
static async exist(email) {
return setTimeout(function() {
return userEmails.includes(email)
},2000)
}
async storeEmail() {
let userExist = await this.exist(this.email)
if (userExist) {
console.log('User exist')
} else {
users.push(this.email)
console.log(userEmails)
}
}
};
let foo = new User({email: 'foo@bar.com',name: 'Foo Bar'})
foo.storeEmail() // this.exist is not a function
User.exist('foo@bar.com') // Works when used inside async function with await
解决方法
当您将类的方法定义为静态成员时,它在使用 this
关键字的实例上不可用。您可以使用类函数中的类名直接调用它,例如 User.exist(this.email)
const userEmails = []
class User {
constructor(fields) {
this.email = fields.email;
this.name = fields.name;
}
static async exist(email) {
return setTimeout(function() {
return userEmails.includes(email)
},2000)
}
async storeEmail() {
let userExist = await User.exist(this.email)
if (userExist) {
console.log('User exist')
} else {
users.push(this.email)
console.log(userEmails)
}
}
};
let foo = new User({email: 'foo@bar.com',name: 'Foo Bar'})
foo.storeEmail() // this.exist is not a function
User.exist('foo@bar.com') // Works when used inside async function with
您需要在静态上下文中调用您的静态函数,因此 User.exist()
而不是 this.exist()
:
const userEmails = []
class User {
constructor(fields) {
this.email = fields.email;
this.name = fields.name;
}
static async exist(email) {
return setTimeout(function() {
return userEmails.includes(email)
},name: 'Foo Bar'})
foo.storeEmail(); // OK
User.exist('foo@bar.com'); // OK
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。