如何使用这样的JavaScript在控制台中显示对象?
我已经定义了一个“动物”原型对象:
2个属性:名称,年龄和1个功能:声音,我需要创建以下从“动物”延伸的对象:牛,绵羊,猫(我可以使用任何名称,年龄),然后覆盖功能“声音”以表示每只动物的每种特定声音:
- 牛具有声音“ moo”
- 绵羊的声音“蜜蜂” 绵羊的声音
- cat具有声音“ Meow” “
我必须使用Console.log打印以下结果:
每种动物的姓名和年龄以及每种动物的声音
我已经组成了:
const Animal = {
Cow: {
name: "Peppa",
age: 12,
sound: function cowSound() {
alert("Moo!");
}
},
Sheep: {
name: "Shirley",
age: 7,
sound: function sheepSound() {
alert("Baa!");
}
},
Cat: {
name: "Felipe",
age: 3,
sound: function catSound() {
alert("Meow!");
}
},
};
console.log(JSON.stringify(Animal))
但结果是: “ {; ; quot;:{; qu来'name; quot; quole; ;
:
; qu来 我需要与Json Stringify一起使用,看看为什么它不在这里显示的声音,谢谢
I have Define a "Animal" prototype object with:
2 properties: name, age and 1 function: sound, I need to create the following objects which are extended from "Animal": Cow, Sheep, Cat (I can use any name and age), then overriding the function "sound" to represent each specific sound of each animal for example:
- Cow has the sound "mooo"
- Sheep has the sound "bee" sheep sound
- Cat has the sound "meow"
I have to use console.log to print the following result:
Name and Age of each type of animal and the sound of each type of animal
I already composed this:
const Animal = {
Cow: {
name: "Peppa",
age: 12,
sound: function cowSound() {
alert("Moo!");
}
},
Sheep: {
name: "Shirley",
age: 7,
sound: function sheepSound() {
alert("Baa!");
}
},
Cat: {
name: "Felipe",
age: 3,
sound: function catSound() {
alert("Meow!");
}
},
};
console.log(JSON.stringify(Animal))
But the result is this:
"{"Cow":{"name":"Peppa","age":12},"Sheep":{"name":"Shirley","age":7},"Cat":{"name":"Felipe","age":8}}"
Which is pretty ugly I must admit
How can I display the way I need it with JSON Stringify and see why the sound it's not displaying here, thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用oloo模式,
您可以使用oloo(链接到其他对象的对象)模式使用 object.create 方法。
使用原型链接
JavaScript实际上没有类,它仅具有功能。 ES6类语法被转移到原型链式函数中,如下所示。
@OEROL使用JS类提供了答案。
阅读
Using OLOO pattern
You can use OLOO (Object linked to other objects) pattern to achieve the inheritance using Object.create method.
Using prototype chaining
Javascript does not have classes actually, it has only the functions. ES6 class syntax gets transpiled into prototype chained functions like below.
@oerol has provided an answer using JS classes.
Read Inheritance and the prototype chain
您可以执行
console.log(Animal)
如果您希望它更可读。但是,正如@Barmar指出的那样,这不是实例化课程的正确方法。一种更合适的方法是:
You can do
console.log(Animal)
if you want it to be more readable.However, as @Barmar pointed out, that is not the correct way to instantiate a class. A more suitable approach would be: