gpt4 book ai didi

javascript - 如何在对象内部创建方法

转载 作者:行者123 更新时间:2023-11-28 17:10:14 25 4
gpt4 key购买 nike

我的家庭作业需要帮助。我不知道如何在对象内部创建一个像他想要的方法:

create a monkey object, which has the following properties: name, species, foodsEaten.

And the following methods:

eatSomething(thingAsString)

introduce: producers a string introducing itself, including its name, species, and what it's eaten.

-Create 3 monkeys total. Make sure all 3 monkeys have all properties set and methods defined.

我已经创建了猴子对象及其属性:

function Monkey(name, species, foodsEaten) {
this.name = name;
this.species = species;
this.foodsEaten = foodsEaten;
}

let monkey01 = new Monkey(chimp, chimpanzee, honey);
let monkey02 = new Monkey(gibb, gibbon, apple);
let monkey03 = new Monkey(babo, babbon, banana);

最佳答案

通常执行此操作的方法是在 Monkey 原型(prototype)上添加一个函数。这将允许所有实例共享相同的功能。在函数中,您可以使用 this 引用实例(假设您从实例调用它,例如 monkey01.eatsomething())。

这里我们将 foodsEaten 设为一个数组,以便您可以跟踪多个数组。然后该方法只是插入 this.foodsEaten:

function Monkey(name, species, foodsEaten) {
this.name = name;
this.species = species;
this.foodsEaten = [...foodsEaten]; // make a copy so you don't mutate the passed in array.

}

Monkey.prototype.eatsomething = function(foodString) {
this.foodsEaten.push(foodString)
}

let monkey01 = new Monkey('chimp', 'chimpanzee', ['honey']);

monkey01.eatsomething("bananna")

// now it's eatne more food
console.log(monkey01.foodsEaten)

对于其他方法,只需做更多相同的事情即可。

关于javascript - 如何在对象内部创建方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54619629/

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