考虑以下代码段:
class Foo {
method = () => {
console.log('method');
}
}
const f = new Foo();
f.method();
工作得很好。但是,如果函数改为异步,则没有其他更改:
class Foo {
method = async () => {
console.log('method');
}
}
const f = new Foo();
f.method();
这会导致语法错误。无论是否使用箭头函数,它都会发生:
class Foo {
method = function() {
console.log('method');
}
}
const f = new Foo();
f.method();
class Foo {
method = async function() {
console.log('method');
}
}
const f = new Foo();
f.method();
我的语法是否不正确,或者类字段中只是禁止了异步函数?
(当然,原型上的普通异步方法也是可能的,但我在问类字段中的异步函数为什么/如何工作)
接受评论的建议async method() => {
也不起作用:
class Foo {
async method() => {
console.log('method');
}
}
const f = new Foo();
f.method();