Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between `this` and `prototype`? javascript oop [duplicate]

Tags:

javascript

oop

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?

like image 930
Alex Avatar asked Oct 19 '13 17:10

Alex


People also ask

What is the difference between Proto and prototype in JS?

prototype is a property of a Function object. It is the prototype of objects constructed by that function. __proto__ is an internal property of an object, pointing to its prototype.

Is .prototype same as this?

In most cases they are essentially the same, but the second version saves memory because there is only one instance of the function instead of a separate function for each object.

What is the difference between class and prototype in JavaScript?

Classes. The most important difference between class- and prototype-based inheritance is that a class defines a type which can be instantiated at runtime, whereas a prototype is itself an object instance.

What is the advantage of prototype in JavaScript?

Prototypes allow you to easily define methods to all instances of a particular object. The beauty is that the method is applied to the prototype, so it is only stored in the memory once, but every instance of the object has access to it.


2 Answers

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.

like image 141
Denys Séguret Avatar answered Oct 17 '22 05:10

Denys Séguret


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

like image 20
Xitalogy Avatar answered Oct 17 '22 05:10

Xitalogy