
JavaScript has become one of the most dominating programming languages of modern software development era. From browser client side development to server side development(nodejs) to mobile app development(phonegap), it’s everywhere.
However, unfortunately, it doesn’t provide traditional object-oriented API. May be that’s why everywhere all we see functional styled straight forward JavaScript/jQuery, which bear higher risks of messy codes. If you have experience as front end dev, I hope you already seen this and/or have already written some yourself as well.
To rescue us, platform like typescript arises to give us taste of a little more object orientated tastes in writing more organized JavaScript. But they require some additional effort too, such as compiling them back to pure JavaScript before getting them in action.
But, it’s still possible to write direct JavaScript in a little more better object-oriented way. Today, we will the JavaScript class basics to write code more better and organized.
My code examples used in this tutorial are tested in only nodejs environment. Please let me know if you are having issue in any other place so that I can check and update the article accordingly.
Declaring A Class:
Well, the first thing you need to know: There is no ‘class’ keyword in javascript(well, yet). Though it is supposed to be supported in JavaScript 2.x, still JavaScript 1.x is used in all places.
So, what do we do? Simple, the well-known ‘function’ keyword will do the job here. It will also act as a class constructor as well(2-in-1! bravo). And fortunately, we do have support for ‘new’ keyword. So, here we go:
function MyJSClass(name) { this.name = name; } var obj = new MyJSClass("test name"); console.log(obj.name); //prints "test name"
as you can see on the above code snippet, we are declaring a class, which takes a single ‘name’ parameter as its constructor. Then assigning a variable with a new instance of this class. after creation of the instance, it has a single attribute named ‘name’.
Now, a question is very usual to come in mind that, as the class definition is defined by a function definition, can’t we just call the by method name and get the instance? The answer is ‘No’. That’s where the wonder of ‘new’ keyword comes in. Lets try this:
var obj = MyJSClass("without new"); console.log(obj.name); //throws error: //TypeError: Cannot read property 'name' of undefined
Hmm, so is there any way around to get this done without help of ‘new’ keyword. Answer is yes, there is a way like follows(though I recommended the earlier way more):
function MyJSClass(name) { //this part will create a new instance if 'new' keyword wasn't used //while calling this function if(!(this instanceof MyJSClass)) { return new MyJSClass(name); } this.name = name; }
Private/Public Property/Attribute?
Well second thing: There is no apparent private/public keyword support in JavaScript. Thus not supporting encapsulation in traditional way. So, any property you declare as this.{attr_name} can be accessed always by {instance}.{attr_name} accessor. However, as alternative, we can declare variables using ‘var’ keyword, which will be treated as local variable and can’t be accessed from outside. I am not saying you can get the full object-oriented flavor in that way, but could partially help sometimes.
function MyJSClass(name) { var privateProperty = "only for local scope"; this.name = name; } var obj = new MyJSClass("test name"); console.log(obj.name); //prints "test name" console.log(obj.privateProperty); //prints "undefined"
Getter/Setter For Attributes:
Good thing, we have getter setter support in JavaScript. Lets see a simple example to calculate full name from first-name/last-name and age from birth date and access them using getter/setter:
function MyJSClass(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } MyJSClass.prototype = { get FullName(){ return this.firstName+" "+this.lastName; }, set BirthDay(bDay) { this.bDay = new Date(bDay); }, get Age(){ //calculate from birthday var ageDifMs = Date.now() - this.bDay.getTime(); var ageDate = new Date(ageDifMs); // miliseconds from epoch return Math.abs(ageDate.getUTCFullYear() - 1970); } } var obj = new MyJSClass("test", "name"); console.log(obj.FullName); //prints "test name" obj.BirthDay = "01/01/1990"; console.log(obj.Age); //prints "24"
a nice abstraction, right?
More To Come:
I am planning to write another tutorial with some additional concepts like inheritance, static method etc very soon. So, keep in touch! Happy programming!
Ali, I have gone through your post and it really helped me alot. Still i have some queries, Can you please tell me about overriding Native Object Methods. Looking for your quick response.
As you may already know from my comment on this post, javascript isn’t built in traditional object oriented way. Same way, overriding doesn’t exist by default here. But you can simulate it by assigning the function to your own definition. Such as “JSON.stringify = function(){ return ‘whatever’;};” will change the native ‘stringify’ method. Check this link: http://jsbin.com/moratunece/2/edit?js,output . Hope this helps!