Prototype to the Rescue, curiosity question


#1


Why do we have to use 'prototype' like this;

function Dog (breed) {
this.breed = breed;
};

// here we make buddy and teach him how to bark
var buddy = new Dog("golden Retriever");
Dog.prototype.bark = function() {
console.log("Woof");
};
buddy.bark();

// here we make snoopy
var snoopy = new Dog("Beagle");
/// this time it works!
snoopy.bark();


Instead of this?(my idea of code...)

function Dog (breed) {
  this.breed = breed;
  this.bark = function() {
  console.log("Woof");
};
};

// here we make buddy and teach him how to bark
var buddy = new Dog("golden Retriever");

buddy.bark();

// here we make snoopy
var snoopy = new Dog("Beagle");
/// this time it works!
snoopy.bark();

tho it works fine.


#2

One of the main reasons for using prototype is to limit the number of methods written into a constructor function so it is brief and concise.

function Dog(breed) {
    this.breed = breed;
}

Dog.prototype.bark = function () {
    console.log("Woof")
};

When we create an instance of the Dog class, all that gets written to the new object is the instance variable. The bark method does not since the instance can reach up the prototype chain to find it, without having to own a copy of the function. This is very efficient use of memory resources.


#3

Thank you very much !


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.