1
    function Animal(animal) {
      this.animal=animal;
      this.bark=function(cry){
        console.log(this.animal+" : "+cry);
      }
    }

    var dog=new Animal("dog");
    var cat=new Animal("cat");
    dog.bark("woof"); // result will be -> dog : woof
    cat.bark("mew"); // result will be -> cat : mew

    // if i want to change both result to hello...
    Animal.bark=function() {
     console.log(`${this.animal} : hello...`);
    }; // it doesn't work

    // if i want to change it, i should change each of it
    dog.bark=function() {
      console.log("dog : hello...");
    };
    cat.bark=function() {
      console.log("cat: hello...");
    };

    // But when i use prototype methods
    function Animal(animal) {
      this.animal=animal;
    };
    Animal.prototype.bark=function(cry) {
      console.log(this.animal+" : "+cry);
    };

    var dog=new Animal("dog");
    var cat=new Animal("cat");
    dog.bark("woof"); // result will be -> dog : woof
    cat.bark("mew"); // result will be -> cat : mew

    // if i want to change both result to hello...
    Animal.prototype.bark=function() {
     console.log(`${this.animal} : hello...`);
    }; // it works well
 

I code a function called Animal to understand prototype concept. This is my question, when i tried to modify the function bark in function Animal, i know it works when i use prototype but i don't know why it does not work when i don't use prototype. How can i understand it well?

Yoon Kim
  • 43
  • 6
  • 1
    This is the defining feature of prototype inheritance vs. classical inheritance: objects share a single prototype, and any property on that prototype is accessible to every instance. Your first `Animal` does not have a custom prototype, it only sets instance values, so each instance has their own, unique, function `bark` and reassigning will _only_ update that instance. Your second `Animal` assigns a prototype with _that_ having a `bark` function, so every instance will fall through to that. – Mike 'Pomax' Kamermans Dec 27 '20 at 00:28
  • JavaScript only searches the prototype chain if there's no property in the object itself. – Barmar Dec 27 '20 at 00:43

0 Answers0