You can not add a new property to an existing object constructor in JavaScript

Rumman Ansari   Software Engineer   2024-09-29 08:05:32   62  Share
Subject Syllabus DetailsSubject Details Login to Open Video
☰ TContent
☰Fullscreen

Table of Content:



function Animal(type, legs, sound) {
    this.animalType = type;
    this.numberOfLegs = legs;
    this.sound = sound;
    this.isPet = false;
}

// Creating instances of the Animal constructor
var dog = new Animal('Dog', 4, 'Bark');
var cat = new Animal('Cat', 4, 'Meow');
var parrot = new Animal('Parrot', 2, 'Squawk');

Animal.prototype.nameOfAnimal = "My pet";

Animal.prototype.makeSound = function() {
    console.log(this.sound);
};

dog.makeSound();
cat.makeSound();
parrot.makeSound();

// console.log(dog.nameOfAnimal);
// console.log(cat.nameOfAnimal);
// console.log(parrot.nameOfAnimal);
// console.log(dog.isPet);
// console.log(cat.isPet);
// console.log(parrot.numberOfLegs);