5

While going through javascript course on codecademy.com, I've become slightly confused.

So first we've been learning how to add method to a Class:

function Dog (breed) {
    this.breed = breed;
    this.sayHello = function () {
        console.log("Hello this is a " + this.breed + " dog");
    }
};
var someDog = new Dog("golden retriever");
someDog.sayHello();

Then we started the "prototype". And there was this example:

function Dog (breed) {
    this.breed = breed;
};
Dog.prototype.sayHello = function () {
    console.log("Hello this is a " + this.breed + " dog");
}
var someDog = new Dog("golden retriever");
someDog.sayHello();

Both examples are giving the same result. Are these two examples are just two ways doing same thing? Or there is a practical difference between two of them?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Alex
  • 283
  • 1
  • 2
  • 12

2 Answers2

7

The difference is that in the second case, all instances share the same sayHello function. That's more efficient, especially if you create a lot of instances.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

The prototype method sayHello is shared by all instances of the class Dog as opposed to adding it with this in the constructor which creates a fresh copy for each instance, wasting space and time.

Here is how the new operator works in words:

https://gist.github.com/Havvy/5037770

Here is how the new operator works using a picture:

enter image description here

Xitalogy
  • 1,592
  • 1
  • 14
  • 17