Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

JVM Languages

Is JavaScript an Object-Oriented Language?


Aug01: Java Q&A

Nadine is an independent contractor and a Sun Certified Java Programmer. She can be contacted at [email protected].


Because JavaScript is not strongly typed and does not support class-based inheritance, it is easy to dismiss it as not being an object-oriented language. In truth, JavaScript is an object-oriented language that utilizes prototype-based inheritance rather than class-based inheritance

In addition to its inheritance capabilities, JavaScript has other, albeit underused, object-oriented strengths such as encapsulation. The concept of encapsulation (that is, making an object's data members private and manipulating that data using methods) can be easily transferred to JavaScript. Just as a typical Java class has a constructor, member variables, and methods, this class structure can be mirrored with JavaScript. This is done by what is known in JavaScript as a "nested function" — a function that houses one or many inner functions.

function OuterMost() {...function nested() {...} ...}

JavaScript refers to nested functions in this context as "methods." For simplicity, I refer to the outermost function as a class. Listing One is an example of a JavaScript class called MyClassName. While the syntax is notably different, the underlying structure achieves the same end goal: encapsulation.

In Java, there is a special kind of method called a "constructor," whose primary purpose is to allocate storage for the object and assign initial values to its properties. In JavaScript, a constructor also exists and even works in the same way, but is not as obvious when examining the language syntax. This is because JavaScript does not contain a formal constructor. Instead, the outermost function serves as a constructor. Consequently, it makes sense to place all initialization code after the property declarations (as in Listing One).

Following the property declarations and object initializations are the method pointers. To handle scoping issues between the outermost function and its nested functions, method pointers are used. Bridging this scoping gap, in turn, lets the method have public access. For every nested function that will have public access, a corresponding method pointer must exist (as in Listing One). Omitting the method pointer will make the method private. This comes in handy and is an important feature of encapsulation. Also, for scoping reasons, the object properties are intentionally not preceded by the keyword this. Omitting the keyword allows them to remain private. Using the this keyword only serves to make the object property public, thereby defying encapsulation.

Listing Two shows how to create an object instance and call its methods. The HTML script tag's src attribute (line 3 of Listing Two) is used to include the contents of myclassname.js (see Listing One) into the HTML file. The rest of the code should look familiar since it closely parallels object creation and method access in Java. This approach is ideal when creating JavaScript widgets. But don't stop there, JavaScript also pairs well with many design patterns. So why hasn't this been available since the onset of JavaScript? The answer is that nested functions have only been around since JavaScript 1.2.

Adopting this approach makes code easier to read, more maintainable, and achieves better reuse. In addition, developers coming from an OO background will find the transition to JavaScript smoother. Be conservative, however, because this approach can also slow things down when used excessively.

Some final words. The ECMAScript specification, to which JavaScript must conform, lists future reserved keywords for proposed extensions. Among them are: class, import, super, and extends. Sound familiar? A glimpse of tomorrow hints that JavaScript may become even more Java-like.

DDJ

Listing One

/* myclassname.js */
function MyClassName(parameterA, parameterB)
{
    // --- Object Properties ---
    propertyR = "propertyR is read only.";
        
    // --- Object Initialization ---
    propertyA = parameterA;
    propertyB = parameterB;
        
    // --- Method Pointers ---
    this.getPropertyA = _getPropertyA;  
    this.setPropertyA = _setPropertyA;
    this.getPropertyB = _getPropertyB;
    this.setPropertyB = _setPropertyB;
    this.getPropertyR = _getPropertyR;
    this.doSomeAction1 = _doSomeAction1;

    // --- Methods ---
    function _getPropertyA()
    {
        return propertyA;
    }
    function _setPropertyA(para)
    {
        propertyA = para;
    }
    function _getPropertyB()
    {
        return propertyB;
    }
    function _setPropertyB(para)
    {
        propertyB = para;
    }
    function _getPropertyR()
    {
        return propertyR;
    }
    function _doSomeAction1()
    {
        alert(aPrivateMethod() + " " + this.getPropertyR());
    }
    function aPrivateMethod()
    {
        return "aPrivateMethod() is a private method.";
    }
}

Back to Article

Listing Two

    <html>
    <head>
    <script src="myclassname.js" language="JavaScript"></script>
    <script language="JavaScript">
        // object declaration and instantiation
        var objMyClassName = null;      
        objMyClassName = new MyClassName("A", "B");
        
        // accessing the newly created objects methods
        alert(objMyClassName.getPropertyA());           // Displays "A"
        alert(objMyClassName.getPropertyB());           // Displays "B"
    
        objMyClassName.setPropertyA("Y");
        objMyClassName.setPropertyB("Z");

   
        alert(objMyClassName.getPropertyA());           // Displays "Y"
        alert(objMyClassName.getPropertyB());           // Displays "Z"

        // Displays aPrivateMethod() is a private method. propertyR is read only.   
        objMyClassName.doSomeAction1(); 
                
        // Displays Undefined - propertyB is private
        alert(objMyClassName.propertyB);

       // Fails, aPrivateMethod() is private.  Netscape quietly bombs. 
       alert(objMyClassName.aPrivateMethod());         
 
    </script>
    </head>
    <body>
        <!-- body tags here -->
    </body>
    </html>



Back to Article


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.