Javascript Concepts Simplified Part 1: Javascript Classes

While the Javascript language offers many of the constructs required for object-oriented programming, they remain largely unused. Today we’ll take a look at how to start with object-oriented programing in Javascript. by defining a class in Javascript. We’ll use the simple HTML file to call our script file,

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
    <head>
        <title>Hello Javascript!</title>
        <script type="text/javascript" src="MyScript.js"></script>
    </head>
    <body>
        Hello Javascript!
    </body>
</html>

Now let’s create a class definition (in MyScript.js). Note that there is no ‘class’ keyword in Javascript, the class definition is just a function definition,

function MyClass() {

    // Public field
    this.aPublicField = "This is a public field of the type MyClass";

    // Private field
    var aPrivateField = "This is a private field of the type MyClass";

    // Public method
    this.aPublicMethod = function() {
        // Use the private method
        if (aPrivateMethod()) { return this.aPublicField; } 
        else { return aPrivateField; }
    }

    // Private method
    function aPrivateMethod() {
        return true;
    }
    
    // Oops! We can expose the private field
    this.exposePrivateField = aPrivateField;
    // and the private method
    this.exposePrivateMethod = aPrivateMethod;
}

// Create an instance of MyClass using the ‘new’ keyword
var myclass = new MyClass();

// Get the public field
alert(myclass.aPublicField);

// Call the public method
alert(myclass.aPublicMethod());

// Call the private field – can’t get to them directly
alert(myclass.exposePrivateField);
alert(myclass.exposePrivateMethod());

So it’s pretty simple to create a class in Javascript. We can also create a runtime field for the class,

// Create an instance of MyClass
var myclass = new MyClass();

// Create a field at runtime
myclass.aRuntimeField = "This is a runtime field of the type MyClass";

// View the field value
alert(myclass.aRuntimeField);

Advertisements

About soumya chattopadhyay
I live and work in Seattle, WA. I work with Microsoft technologies, and I'm especially interested in C#.

2 Responses to Javascript Concepts Simplified Part 1: Javascript Classes

  1. Pingback: Javascript Concepts Simplified « I.Net

  2. Pingback: Javascript Concepts Simplified Part 3: Javascript and JSON « I.Net

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: