• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Programming / Object Oriented JavaScript: Class Basics

Object Oriented JavaScript: Class Basics

October 19, 2014 by Rana Ahsan 2 Comments

Javascript class basics

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!

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Programming Tagged With: javascript, oop

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. sachin says

    November 5, 2014 at 1:24 am

    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.

    Reply
    • Md Ali Ahsan Rana says

      November 7, 2014 at 9:55 pm

      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!

      Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Beginning Codeigniter Application Development
    Beginning Codeigniter Application Development
  • How To Use Hotkeys/Keyboard Events In WPF Application Using C#
    How To Use Hotkeys/Keyboard Events In WPF Application Using C#
  • Control HTML5 Audio With Jquery
    Control HTML5 Audio With Jquery

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023