Reputation: 633
I don't see developers like to use prototype in JS unless the scale of the app is huge. It's because they avoid overuse of prototype function?
any simpler way of writing below logic?
function Dog (breed) {
this.breed = breed;
};
Dog.prototype.bark = function() {
console.log("Woof");
};
var buddy = new Dog("golden Retriever");
buddy.bark();
var snoopy = new Dog("Beagle");
snoopy.bark();
Upvotes: 1
Views: 248
Reputation: 239463
Method 1
function Dog (breed) {
this.breed = breed;
};
Dog.prototype.bark = function() {
console.log("Woof");
};
Advantages:
Dog
, the objects will be created faster since the bark
is already defined in prototype, it will be set in the new object as well.Disadvantages:
Method 2
function Dog (breed) {
this.breed = breed;
this.bark = function() {
console.log(this.breed);
};
};
Disadvantages:
breed
is added to the object itself directly, it is accessible via the object. So, no protection for data.Method 3
function Dog (breed) {
this.bark = function() {
console.log(breed);
};
};
Advantages
breed
within the object, but that cannot be accessed outside the object. So, protection to data.Disadvantages:
Upvotes: 1
Reputation:
function Dog (breed) {//this stuff is private :)
this.breed = breed;
return { //public api
bark: function(){
console.log("Woof");
}
}
};
The advantage of this pattern is it offers privacy.
Upvotes: 1