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?
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.
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.
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With