Prototypes, and why they are awesome.
Before I start, Mozilla can write this guide better than me: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
Just like you I also have a background in traditional OO languages, my first programming language that I really learned was C++, and I thought it was the greatest. In many ways, C++ is a fantastic language, that's why the best JavaScript engine is coded in it.
The difference however, lies in how JavaScript works. C++ is strictly typed, and classes must contain the exact datatypes of what they contain:
class Rectangle {
int width, height;
public:
void set_values (int,int);
int area() {return width*height;}
};
Unlike C++, nearly everything in JavaScript is an Object
and and be easily extended with dot notation
var derek = "Derek Howard";
derek.age = 16;
Since JavaScript is compiled on the fly, it is extremely flexible. Rather than a rigid skeleton of what an Object
can be, we can just extend an existing object whenever we want.
In many situations however, we want to have a whole bunch of Objects that look the same , but have their own data (like a class in C++). This is where the prototype
object comes into play.
How can I make a "class" in Javascript?
I will recreate the rectangle object above in JavaScript to demonstrate.
The first step is to create a Function
that defines your class name. This should be capitalized to signify it is a "class"
The first function (the one that is capitalized) is your constructor. You should use it to pass essential inital values to your Object
function Rectangle(width, height) {
this.width = width || 1;
this.height = height || 1;
}
The ||
operator makes it so if the developer doesn't pass a value to the constructor it still has default values.
Then, to add functions to your "class" you will want to create functions on the prototype.
Rectangle.prototype.area = function () {
return this.width * this.height;
}
You're done creating the class! Now to use your class.
To use the class is actually very similar to C++. You simply create an object and use the new
keyword:
var bigRec = new Rectangle(42, 100);
Then you can call the functions you created on Rectangle.prototype
directly on the new object:
alert(bigRec.area());
//new class
function Rectangle(width, height) {
//class properties
this.width = width || 1;
this.height = height || 1;
}
//class functions
Rectangle.prototype.area = function () {
return this.width * this.height;
}
//create a new Rectangle object
var bigRec = new Rectangle(42, 100);
//call functions created from the prototype
alert(bigRec.area());