Different between a protoype vs adding a method in the constructor


#1

Please see -----A and -----B, are they the same? If they are, what is the purpose of proto-type?

function Dog (breed) {
this.breed = breed;
this.bark = function() { // the same as protoype ----- A
console.log("Woof");
};
}
// here we make buddy and teach him how to bark
var buddy = new Dog("golden Retriever");
Dog.prototype.bark = function() { //same as the method added in the "Dog" constructor?? ----- B
console.log("Woof");
};
buddy.bark();

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


#2

proto type extends an object, so you can add methods later, if, for whatever reason you can't add it directly to the constructor.


#3

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