gpt4 book ai didi

javascript - 学习 OOP Javascript,我真的很努力,但它并没有陷入困境。任何人都可以帮我解决这个问题吗?

转载 作者:行者123 更新时间:2023-11-30 09:10:45 24 4
gpt4 key购买 nike

所以,我从这个开始。我想,Worker 是我的类

    function Worker(firstName, lastName, role, action) {
this.firstName = firstName;
this.lastName = lastName;
this.role = role;
this.action = action;
Worker.random = function (name) {
name = this.name
let actions = this.action
console.log(Math.floor((Math.random() * name.action)))
}


}

现在我想在这里用它制作一个"new"对象,

let Stanley = new Worker('Stanley', 'Hudson', 'Sales', [
'Did I Stutter?? You and Michael drink 3.',
'You just had a heart attack and every time Michael opens his mouth you\'re stress levels to up. Drink 4 to calm your nerves',
'Your cheating has caught up with you. Bad Stanley. Drink 2'
])

我如何才能做到 Stanley.random() 并从 Action 数组中取回随机 Action ?我希望能够对任何字符使用 random() 函数。我真的不知道该怎么做?这是重点吧?能够一遍又一遍地使用这些方法?

我知道我很笨,如果你想告诉我,请随意,只要知道我知道就行了。任何帮助,非常感谢

最佳答案

您可以将函数分配给类属性以及常规数据。因此,您需要将 this.random 分配给函数,而不是 Worker.random.. 这样的事情应该可以解决问题..

function Worker(firstName, lastName, role, action) {
this.firstName = firstName;
this.lastName = lastName;
this.role = role;
this.action = action;
this.random = function() {
if (this.action.length > 0) {
return this.action[Math.floor(Math.random() * this.action.length)];
}
};
}

let Stanley = new Worker("Stanley", "Hudson", "Sales", [
"Did I Stutter?? You and Michael drink 3.",
"You just had a heart attack and every time Michael opens his mouth you're stress levels to up. Drink 4 to calm your nerves",
"Your cheating has caught up with you. Bad Stanley. Drink 2"
]);

let randomAction = Stanley.random();
console.log("Random Action From Stanley:", randomAction);

关于javascript - 学习 OOP Javascript,我真的很努力,但它并没有陷入困境。任何人都可以帮我解决这个问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59292215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com