CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • 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
Home Programming Object Oriented JavaScript: Class Basics

Object Oriented JavaScript: Class Basics

Rana Ahsan October 19, 2014 2 Comments


 Object Oriented 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!

Related

Filed Under: Programming Tagged With: javascript, oop

About Rana Ahsan

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

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.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • PHP HTML5 Video Streaming Tutorial
  • How To Work With JSON In Node.js / JavaScript
  • Generate HTTP Requests using c#
  • How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
  • How To Work With CodeIgniter Pagination
  • LinQ To SQL Database Update Operations In C#
  • Get Facebook C# Api Access Token
  • How To Work With Multithreaded Programming In C#.NET Application
  • Control HTML5 Audio With Jquery

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • intolap on PHP HTML5 Video Streaming Tutorial
  • manishpanchal on PHP HTML5 Video Streaming Tutorial
  • Rana Ghosh on PHP HTML5 Video Streaming Tutorial
  • ld13 on Pipe Email To PHP And Parse Content
  • Daniel on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2021 · CodeSamplez.com ·

Copyright © 2021 · Streamline Pro Theme on Genesis Framework · WordPress · Log in