JavaScript does not have language support for classes in the same way that Java does[1]
In JavaScript, functions play the role of..well.. plain old functions and also to create class-like entities.For this post, we are interested in the latter. When a function is invoked with the "new" keyword, it returns an object i.e. it acts as a constructor.
Lets look at an example:
1 2 3 4 5 6 7 8 9 | var Car = function(numGears){ this.numGears = numGears; this.drive = function(){ console.log("driving"); } }; var myCar = new Car(4); myCar.drive() //driving |
Lets add a stop() method to that
1 2 3 | myCar.stop = function(){ console.log("stop"); } |
1 2 | var yourCar = new Car(5); yourCar.stop();// TypeError: Object [object Object] has no method 'stop' |
console.log(Car.prototype);// Object {}
The prototype property is available on all functions, but make sense only for functions that are used as constructors. The reason will be obvious when you understand their role.The prototype property on functions point to an object which serves as the the blueprint of the objects created using that function. The newly created objects have a secret link to this blueprint.But why is it empty in the example .. shouldnt we be seeing a drive() method on it ?
No, because we did not leverage this prototype property to add the method to this blueprint. Look back at the first code snippet, the drive() method is defined like so:
this.drive = function(){..This results in every car instance getting its own copy of the drive() method. (Obviously this is not very efficient. We will correct this later.)
To understand how the prototype property works, lets add stopping functionality to the Car.
1 2 3 4 | Car.prototype.stop = function(){ console.log("stop"); } yourCar.stop(); // stop |
So, that worked.
Lets paint a picture to remember this better
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var Car = function(numGears){ // per-instance properties this.numGears = numGears; }; // shared code on prototype Car.prototype.drive= function(){ console.log("driving"); } Car.prototype.stop = function(){ console.log("stop"); } var myCar = new Car(3) myCar.drive(); // driving myCar.stop(); // stop |
In another post, I will explore how code is shared by inheritance using the class style paradigm
[1] In the next version of the language i.e. in ES2015 / ES6, you can create classes using the class keyword. Here is a link where you you learn more about it:
Classes in JavaScript - My understanding is that it is mostly syntactic sugar that transforms into the above code.
[2] I originally intended to write about the Dojo
declare feature, hence the url of this page name reads as "dojo-declare". The declare module in Dojo is used for creating Java-style classes. The widget framework - Dijit uses this heavily.

No comments:
Post a Comment