Prototypes are pretty confusing thing in JavaScript, but like everything else in programming, one needs to understand them. Creating this page was a pairing challenge and neither me or my pair knew much about prototypes going in. We had to do quite a research to create a whole page dedicated especially to this subject. In our search for the truth about prototypes we came to realisation that they are crucial when we would like to implement inheritance.
When we look at language like Ruby, where inheritance is a link between classes, everything seems pretty straight forward. Create first class, put some methods in, and when creating another class, make it 'less than' first one and the second class gets all the methods from the first one.
This isn't so easy in JavaScript, and the main reason is that it doesn't have classes, it only has objects. And objects in JavaScript mostly have property/value pairs, and not only methods like in Ruby. What we need to do to inherit this values or methods from object1 to object2 is to use a special '__proto__' object.
So how it works?
object2.__proto__ = object1;
Would make object2 get everything object1 has.
There's another way to inherit from object, and this one is more recommended as '__proto__' isn't part of standard interface of JavaScript. We can assign our object to inherit right at the creation of it. Like so:
var object2 = Object.create(object1);
This achieves the same effect as previous example.
There are many pages that explain this concept in detail, and they explain it very well. We gathered some for you to have a look if you're intersted in it.
new
it makes a new object and initializes the new object with a prototype. The primary responsibilities of JavaScript's prototypes are:
var Animal = function (name, type, sound) {
this.name = name;
this.type = type;
this.sound = sound;
};
Animal.prototype = {
makeNoise: function () {
return this.sound + " is the sound that " + this.name + " makes!";
},
getWeightAtAge: function(age) {
if (this.type === "dog"){
return 5 * age;
} else if (this.type == "fish"){
return 2 * age;
} else {
return age;
}
},
toString: function () {
return this.name + " is a " + this.type;
}
}
Schlinkert created a new variable called Animal, setting it equal to a function that takes the following parameters: name, type and sound. The purpose of the Animal function is to initialize methods of our prototype. Notice how JavaScript used this
? Within JavaScript, this
is the equivalent of Ruby's self
. JavaScript's initialize function goes outside the phototype, and contrary to JavaScript, Ruby's initialize method goes within the Ruby class. The three functions defined by Schlinkert, makeNoise
, getWeightAtAge
and toString
, belong to the instances of the JavaScript objects.