Prototype to the Rescue


#1


https://www.codecademy.com/courses/objects-ii/2/4?curriculum_id=506324b3a7dffd00020bf661


If I had 10 dogs and used a function that required bark on dog 1, however prototype was not used till dog 5... will my bark function on dog 1 still activate? (considering there is no function till dog 5)

Simply put.... does the prototype feature only activate with the line is reached? meaning the property is not available till it is reached?


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();


#2

its a sillly question I know


#3

this:

var buddy = new Dog("golden Retriever");

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

Dogs have learned how to bark yet. If you call bark before you learned it to the dogs, you will get an error.

Prototype will add the method once it is reached. So, you might create 5 instances first, then add bark method.

The most important in this case, is when you call bark (to make the dog actually bark)


#4

what is the need for prototype here?

we can simply use
Dog.bark = function () {
console.log("Woof");
};


#5

because doing what you suggest gives an error. We need propotype to extent our Dog function


#6

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