
JavaScript has become one of the most dominating programming languages in modern software development. It’s everywhere, from browser client-side development to server-side development (Nodejs) to mobile app development(PhoneGap). Unfortunately, it doesn’t provide a traditional object-oriented javascript API much.
Maybe that’s why we see functional-styled, straightforward JavaScript/jQuery everywhere, which carries higher risks of messy codes. If you have experience as a front-end developer, I hope you have already seen this and/or have already written some yourself.
To rescue us, a platform like TypeScript has arisen to give us a little more object-oriented JavaScript taste in writing more organized JavaScript code. However, they require some additional effort, too, such as compiling them back into pure JavaScript before getting them into action.
But it’s still possible to write direct JavaScript in a better, more object-oriented way. Today, we will review the JavaScript class basics to write better, more organized code.
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 is that there is no ‘class’ keyword in JavaScript (well, yet). Though it is supposed to be supported in JavaScript 2.x, JavaScript 1.x is used everywhere.
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). Fortunately, we do have support for the ‘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"
Code language: JavaScript (javascript)
As you can see in the above code snippet, we are declaring a class that takes a single ‘name’ parameter as its constructor. Then, assign a variable with a new instance of this class. After the instance is created, it has a single attribute named ‘name’.
Now, a ubiquitous question comes to mind: as a function definition defines the class definition, can’t we just call the by-method name and get the instance? The answer is ‘No’. That’s where the wonder of the ‘new’ keyword comes in. Let’s try this:
var obj = MyJSClass("without new");
console.log(obj.name);
//throws error:
//TypeError: Cannot read property 'name' of undefined
Code language: JavaScript (javascript)
Hmm, so is there any way around to get this done without the help of the ‘new’ keyword? The answer is yes; there is a way like the following (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;
}
Code language: JavaScript (javascript)
Private/Public Property/Attribute?
The second thing is that there is no apparent private/public keyword support in JavaScript. Thus, it does not traditionally support encapsulation. So, any property you declare as this. {attr_name} can always be accessed by {instance}. {attr_name} accessor. However, as an alternative, we can declare variables using the ‘var’ keyword, which will be treated as a local variable and can’t be accessed from outside. I am not saying you can get the full object-oriented flavour in that way, but it 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"
Code language: JavaScript (javascript)
Getter/Setter For Attributes:
It’s a good thing we have getter setter support in JavaScript. Let’s 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"
Code language: JavaScript (javascript)
A nice abstraction, right?
Final Words:
If you liked this article, you might also like this one on Javascript static methods as well. Keep in touch! Happy programming!
Discover more from CodeSamplez.com
Subscribe to get the latest posts sent to your email.
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!