How do we handle “classes” with JavaScript?
Some people says that JS is not object-oriented. But yes, it is. The difference between JS and some others OOP languages is that there are not “classes” in JS. There are “constructors” and “prototypes”.
Constructors
Nothing more than simple functions. You can create an instance by simply calling the function with the new keyword before. Now, by default, the function (then called constructor) returns an instance, a new object.
// create the constructor
function MyConstructor() {
}
// create a new instance
var myInstance = new MyConstructor();
Ok. And where are the methods, properties and all those stuff?
Like any other function, we can use arguments and put their values into the instance, that is referenced inside the constructor by the name this. Firstly, the instance is nothing more than a writable object; so you can add anything you want to it.
function Car(color) {
// now the instance have the property 'color'
this.color = color;
}
var myCar = new Car('red');
Prototypes
The instances also can inherit a bunch of defined stuff. Here we go, prototyping. Now we can predefine methods that can be used directly from the instance. So, every instance – including the already created ones – will have the stuff defined into their constructor’s prototype.
function Car(color) {
this.color = color;
}
var myCar = new Car('red');
Car.prototype.changeColor = function (color) {
this.color = color;
};
// now, myCar.color = 'blue'.
myCar.changeColor('blue');
We can write any object-oriented app with JavaScript, following the constructor-prototype concept; but some people just don’t like this concept. Therefore, they can use some script that “simulates” the classic class syntax. Sometimes it can make our code more organized. It’s not a huge advantage at all, but just coding preferences: nothing that we can’t do with pure prototyping.





