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:
functionMyJSClass(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 undefinedCode 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):
functionMyJSClass(name)
{
//this part will create a new instance if 'new' keyword wasn't used //while calling this functionif(!(thisinstanceof MyJSClass)) {
returnnew 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.
functionMyJSClass(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:
functionMyJSClass(firstName, lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
MyJSClass.prototype = {
get FullName(){
returnthis.firstName+" "+this.lastName;
},
set BirthDay(bDay) {
this.bDay = newDate(bDay);
},
get Age(){
//calculate from birthdayvar ageDifMs = Date.now() - this.bDay.getTime();
var ageDate = newDate(ageDifMs); // miliseconds from epochreturnMath.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)
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!
[…] is a follow-up article to my earlier post on JavaScript class basics. There are a few more things that we actually need to dive into object-oriented programming in […]
var JetpackInstantSearchOptions=JSON.parse(decodeURIComponent("%7B%22overlayOptions%22%3A%7B%22colorTheme%22%3A%22light%22%2C%22enableInfScroll%22%3Atrue%2C%22enableFilteringOpensOverlay%22%3Atrue%2C%22enablePostDate%22%3Atrue%2C%22enableSort%22%3Atrue%2C%22highlightColor%22%3A%22%23FFC%22%2C%22overlayTrigger%22%3A%22submit%22%2C%22resultFormat%22%3A%22expanded%22%2C%22showPoweredBy%22%3Atrue%2C%22defaultSort%22%3A%22relevance%22%2C%22excludedPostTypes%22%3A%5B%5D%7D%2C%22homeUrl%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%22%2C%22locale%22%3A%22en-US%22%2C%22postsPerPage%22%3A5%2C%22siteId%22%3A18994550%2C%22postTypes%22%3A%7B%22post%22%3A%7B%22singular_name%22%3A%22Post%22%2C%22name%22%3A%22Posts%22%7D%2C%22page%22%3A%7B%22singular_name%22%3A%22Page%22%2C%22name%22%3A%22Pages%22%7D%2C%22attachment%22%3A%7B%22singular_name%22%3A%22Media%22%2C%22name%22%3A%22Media%22%7D%7D%2C%22webpackPublicPath%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%5C%2Fwp-content%5C%2Fplugins%5C%2Fjetpack%5C%2Fjetpack_vendor%5C%2Fautomattic%5C%2Fjetpack-search%5C%2Fbuild%5C%2Finstant-search%5C%2F%22%2C%22isPhotonEnabled%22%3Afalse%2C%22isFreePlan%22%3Atrue%2C%22apiRoot%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%5C%2Fwp-json%5C%2F%22%2C%22apiNonce%22%3A%22155bc22a78%22%2C%22isPrivateSite%22%3Afalse%2C%22isWpcom%22%3Afalse%2C%22hasOverlayWidgets%22%3Afalse%2C%22widgets%22%3A%5B%5D%2C%22widgetsOutsideOverlay%22%3A%5B%5D%2C%22hasNonSearchWidgets%22%3Afalse%2C%22preventTrackingCookiesReset%22%3Afalse%7D"));
sachin says
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.
Md Ali Ahsan Rana says
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!