Tengo Definir un objeto prototipo "Animal" con:
2 propiedades: nombre, edad y 1 función: sonido, necesito crear los siguientes objetos que se extienden desde "Animal": Vaca, Oveja, Gato (puedo usar cualquier nombre y edad), luego anulo la función "sonido" para representar cada sonido específico de cada animal por ejemplo:
Tengo que usar console.log para imprimir el siguiente resultado:
Nombre y Edad de cada tipo de animal y el sonido de cada tipo de animal
Ya compuse esto:
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))Pero el resultado es este: "{"Vaca":{"nombre":"Peppa","edad":12},"Oveja":{"nombre":"Shirley"," edad":7},"Gato":{"nombre":"Felipe","edad":8}}"
Lo cual es bastante feo, debo admitir
¿Cómo puedo mostrar la forma en que lo necesito con JSON Stringify y ver por qué el sonido no se muestra aquí? Gracias de antemano.
Puede usar el patrón OLOO (Objeto vinculado a otros objetos) para lograr la herencia usando el método Object.create .
const Animal = { init: function(name, sound) { this.name = name; this.sound = sound; }, makeSound: function() { console.log(`${this.name} has the sound "${this.sound}"`); }, }; // inheritance via Object.create const Cow = Object.create(Animal); const Sheep = Object.create(Animal); const Cat = Object.create(Animal); // any other methods specific to Cat Cat.purr = function() { conslo.log(`${this.name} "purrs"`); }; const animals = []; // initializing objects var cow = Object.create(Cow); cow.init("Cow", "moop"); animals.push(cow); var sheep = Object.create(Sheep); sheep.init("Sheep", "bee"); animals.push(sheep); var cat = Object.create(Cat); cat.init("Cat", "meow"); animals.push(cat); // printing animals.forEach((animal) => { animal.makeSound(); });Javascript no tiene clases en realidad, solo tiene funciones. La sintaxis de la clase ES6 se transpila en prototipos de funciones encadenadas como se muestra a continuación. @oerol ha proporcionado una respuesta usando clases JS.
Lea Herencia y la cadena de prototipos
function Animal(name, sound) { this.name = name; this.sound = sound; } Animal.prototype.makeSound = function() { console.log(`${this.name} has the sound "${this.sound}"`); }; // inheritance via prototype chaining function Cow(name, sound) { Animal.call(this, name, sound); } Cow.prototype = Object.create(Animal.prototype); function Sheep(name, sound) { Animal.call(this, name, sound); } Sheep.prototype = Object.create(Animal.prototype); function Cat(name, sound) { Animal.call(this, name, sound); } Cat.prototype = Object.create(Animal.prototype); Cat.prototype.purr = function() { conslo.log(`${this.name} "purrs"`); }; // initializing new objects const animals = [] var cow = new Cow("Cow", "mooo"); animals.push(cow) var sheep = new Sheep("Sheep", "bee"); animals.push(sheep) var cat = new Sheep("Cat", "meow"); animals.push(cat) // printing animals.forEach((animal) => { animal.makeSound(); });Puedes hacer console.log(Animal) si quieres que sea más legible. Sin embargo, como señaló @Barmar, esa no es la forma correcta de instanciar una clase. Un enfoque más adecuado sería:
class Animal { constructor(name, age) { this.name = name; this.age = age; } sound() { alert("Make Sound"); } } class Cow extends Animal { sound() { alert("Moo!"); } } class Sheep extends Animal { sound() { alert("Meh!"); } } class Cat extends Animal { sound() { alert("Miau!"); } } let cow = new Cow("Peppa", 12) // Create a new object cow.sound() // "Moo!" console.log(cow) // Cow { name: 'Peppa', age: 12 }