【发布时间】:2021-05-30 17:50:21
【问题描述】:
我有这种类型的Child 构造函数。功能游戏必须在每一秒之后减少饥饿并增加乐趣,这被作为一个参数。如果乐趣为 10 或饥饿为 1,则必须停止。
函数need 必须返回当前的乐趣和饥饿。如果我想等待play(),如果有任何待处理,我有一个问题,就像在我的代码中一样。你能帮忙吗?
play 中的参数决定了孩子玩了多少秒 - 例如如果有3个,乐趣会增加+3
function Person(firstName, lastName, age, type, hunger) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.type = type;
this.hunger = hunger;
}
function Child(firstName, lastName, age, type, hunger) {
Person.call(this, firstName, lastName, age, type, hunger)
this.fun = 5
}
Child.prototype = Object.create(Person.prototype)
Child.prototype.constructor = Child
Child.prototype.play = async function (sec) {
const interval = setInterval(() => {
if (this.fun >= 10 || this.hunger <= 1) {
clearInterval(interval)
} else {
this.fun += 1
this.hunger -= 1
}
}, 1000)
setTimeout(() => clearInterval(interval), sec * 1000)
}
Child.prototype.need = async function () {
await this.play()
return "Fun: " + this.fun + " , hunger: " + this.hunger
}
const child1 = new Child("child1", "childdddd", 3, 'boy', 4)
child1.play(3)
console.log(child1.need())
【问题讨论】:
-
你不能。 JS 是单线程的。所以你必须要么使用承诺要么使用回调
-
看不出这跟构造函数有什么关系?
-
谢谢你们,答案在下面:)
标签: javascript oop prototype prototypal-inheritance