user3057928
user3057928

Reputation: 633

best practice to use or not to overuse prototype in Javascript

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

Answers (2)

thefourtheye
thefourtheye

Reputation: 239463

Method 1

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

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

Advantages:

  1. If you create more objects of 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:

  1. It cannot protect the data members. Since, the function is defined separately from other data members, it cannot be in closure scope.

Method 2

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

Disadvantages:

  1. Every time you create an object, the function has to be created. So, performance overhead.
  2. Since, 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

  1. With the help of closures, you can access breed within the object, but that cannot be accessed outside the object. So, protection to data.
  2. No extra variable :)

Disadvantages:

  1. Every time you create an object, the function has to be created. So, performance overhead.

Upvotes: 1

user1403947
user1403947

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

Related Questions