2020-12-27

Javascript prototype methods vs object methods

    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?



from Recent Questions - Stack Overflow https://ift.tt/2Ktm4o9
https://ift.tt/eA8V8J

No comments:

Post a Comment