I would like to know what is the difference between overriding methods with prototypes and without prototypes. Consider:
Example 1:
function Animal() {
this.sleep = function () {
alert("animal sleeping");
};
this.eat = function () {
alert("animal eating");
};
}
function Dog() {
this.eat = function () {
alert("Dog eating");
};
}
Dog.prototype = new Animal;
var dog = new Dog;
dog.eat();
Example 2:
function Animal() { }
function Dog() { }
Animal.prototype.sleep = function () {
alert("animal sleeping");
};
Animal.prototype.eat = function () {
alert("animal eating");
};
Dog.prototype = new Animal;
Dog.prototype.eat = function () {
alert("Dog eating");
};
var dog = new Dog;
dog.eat();
I feel both examples produce the same effect that the Dog
class is overriding the eat method of the Animal
class. Or is there anything different happening?
In the first method each of the Animal
instance will get its own implementation of sleep
and eat
methods.
While in the second model All instances will share the same instance of the sleep
and eat
methods.
The second model is better since we can share the methods.
As Arun mentioned in the first example you're creating sleep
and eat
functions for each new instance. In the second example there's only one sleep
and eat
function which is shared amongst all the instances.
In this case the second method is better, but it's good to know when to use the first method and when to use the second. A little bit of theory first:
Note: There are four kinds of variables in JavaScript - private
, public
, shared
and static
.
Private variables are inaccessible outside of the function in which they are defined. For example:
function f() {
var x; // this is a private variable
}
Public variables are defined on the this
object inside a function. For example:
function f() {
this.x; // this is a public variable
}
Shared variables are shared on the prototype
of the function. For example:
function f() {}
f.prototype.x; // this is a shared variable
Static variables are properties of the function itself. For example:
function f() {}
f.x; // this is a static variable
Most often it's best to declare the methods of a constructor function as shared methods since all instances of the constructor share them. However if your method needs to access a private variable then it must be declared as a public method itself.
Note: This is my own nomenclature. Not many JavaScript programmers adhere to it. Others seem to follow Douglas Crockford's nomenclature: http://javascript.crockford.com/private.html
To know more about prototypal inheritance in JavaScript read the following answer: https://stackoverflow.com/a/8096017/783743
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