一只甜甜圈
2022-12-29 16:25:41
我的問題與此類似。但我想將 async 關(guān)鍵字放在原型函數(shù)中,而不是構(gòu)造函數(shù)中。“this”在原型函數(shù) saySomething 中未定義。為什么?我如何在課堂上使用異步?var Person = function() { console.log("CALLED PERSON")};Person.prototype.saySomething = async () => { console.log(this);//undefined};(async function(){ var ape = new Person(); await ape.saySomething();}());
1 回答

慕俠2389804
TA貢獻1719條經(jīng)驗 獲得超6個贊
你不應(yīng)該使用箭頭函數(shù)表達式(因為它沒有自己的綁定this
),而是一個正則函數(shù)表達式:
var Person = function() {
console.log("CALLED PERSON")
};
Person.prototype.saySomething = async function() {
console.log(this);
};
(async function(){
var ape = new Person();
await ape.saySomething();
}());
或另一個使用類的示例(如@nickf 所建議的):
class Person {
constructor() {
console.log("CALLED PERSON")
}
async saySomething() {
console.log(this);
};
}
(async function(){
var ape = new Person();
await ape.saySomething();
}());
添加回答
舉報
0/150
提交
取消