» JavaScript Is Not “Truly” Object Oriented

What do you mean? You are wrong, JavaScript is an Object Oriented Programming language!

NO… IT’S… NOT!

If anyone else tries to tell you that, you need to slap them! It has object-oriented like features but it is not object-oriented in nature!

Prove it!

Classical definitions for object-oriented programming languages usually talk about two main features that make a language object-oriented:

1) Encapsulation

In computer science, the principle of information hiding [aka encapsulation] is the hiding of design decisions in a computer program that are most likely to change, thus protecting other parts of the program from change if the design decision is changed. The protection involves providing a stable interface which shields the remainder of the program from the implementation (the details that are most likely to change).WIkipedia

JavaScript does not support information hiding.  There are neither “true” private nor protected members/methods. Everything is public!

If I create an “Object” in JavaScript, any properties I put in that object can be accessed and modified by anyone who has a handle on that object!

2) Polymorphic Inheritance

More precisely, polymorphism (object-oriented programming theory) is the ability of objectstypes to respond to method calls of the same name, each one according to an appropriate type-specific behavior. The programmer (and the program) does not have to know the exact type of the object in advance, so this behavior can be implemented at run time (this is called belonging to different late binding or dynamic binding). — Wikipedia

Polymorphic inheritance is the main driving reason that gives Java and C++/C# its user base.  It allows for an easy way for code reuse and object generalization. From the sub-class, you can access members and methods of the super-class; JavaScript can’t do this.

The reason for this is explained by the differences between HAS-A and IS-A object relationships

IS-A relationships contain a hierarchy of objects where any sub-class of an object IS also a type of the super-class!

When ObjectB extends another ObjectA, the type of the ObjectB is both ObjectB and ObjectA! That way I can make other objects that pass around ObjectA’s which may or may not be my ObjectB!

Think of the classical Shape example. There are a bunch of shapes out there and they all share some properties, but they do have many different properties that they don’t share. Well why not put the shared properties into a super-class and have shapes sub-class them.

// Shape base Object
public class Shape {
    protected String name = "Shape";
    protected int sides = 0;

    public String toString() {
        return this.name + " (" + this.sides + " sides)";
    }
}

public class Square extends Shape {
    public Square() {
        this.name = "Square";
        this.sides = 4;
    }

    public String toString() {
        return "It's hip to be a " + super.toString();
    }
}

public class Driver {
    public static void main( String [] args ) {
        Shape myShape = new Square();
        System.out.println( myShape );
    }
}

In the above example we can create a Shape object (myShape) and set it to a new Square. Why does this work? IS-A relationships dictate that since Square extends Shape, Square must also be a Shape. Therefore, we can store sub-classes of Shape into a Shape object reference and it will work fine.

Moreover, when the toString() method is called on myShape, dynamic binding helps to correctly call the Square.toString() method instead of Shape.toString()!

HAS-A relationships exists via a form of object composition (where 1 object contains another object and uses it’s methods).

In JavaScript, “extending an object” (doesn’t really exist) means just appending the super-objects members and methods to the sub-object. It’s really not any more difficult than that; you can’t ask or test a JavaScript Object if it is both the super-object and sub-object types.

This is called prototypal inheritance.

// Shape base Object
var Shape = function() {
    this.name = "Shape";
    this.sides = 0;

    this.toString = function() {
        return this.name + " (" + this.sides + " sides)";
    };
};

var Square = function() {
    this.name = "Square";
    this.sides = 4;
};

// Starts the HAS-A relationship
Square.prototype = new Shape();

// Test new Square
alert( new Square() );

If you needed to access anything from the super-object, there is no way of doing that using JavaScript’s object model unless you followed object composition where Square carried around an instance of Shape.

Moreover there is no way create a Shape reference and have it stored as a Square as in the previous Java example because HAS-A relationships dictate that members and methods are only appended to sub-classes.

Why Did You Even Write This Article?

I am tired of people writing stuff in/about JavaScript and calling it Object Oriented without explaining the difference between true object-oriented languages and scripting languages like JavaScript.

OOP Developers trying to learn JavaScript need to understand the fundamental difference between Java and JavaScript (is-a vs. has-a); just because JavaScript has “Java” in the name doesn’t mean it’s anyway related to Java.

1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 2.00 out of 5)
Loading ... Loading ...

4 Responses to “JavaScript Is Not “Truly” Object Oriented”


  1. 1 Caligula

    > I am tired of people writing stuff in/about JavaScript and calling it Object Oriented without explaining the difference between true object-oriented languages and scripting languages like JavaScript.

    And I’m tired of people believing that OO means only one thing.

    Is Smalltalk OO? Of course it is–but most implementations have no concept of private variables, instead relying on convention. There’s also instVarAt: and instVarAt:put: messages.

    Is Self OO? Of course it is–it’s also a prototypal-inheritance language.

    (And what’s a “scripting language”?)

  2. 2 Michael Alexander

    Dear Mr. Caligula

    I find your position untenable. If we all attach our own meaning and definitions to words, what’s the point of having a dictionary and how do we communicate efficiently and effectively with one another?

    I’m not familiar with Small Talk. Are you saying it doesn’t support encapsulation and dynamic binding?

    Re your last question, if it was sincere and not rhetorical, a scripting language is a language used to control another piece of software, in the case of JavaScript, the software is the browser.

    Peace

  3. 3 Eric Hamilton

    Javascript is very commonly misunderstood in this way. It actually does support encapsulation via enclasures. JQuery makes heavy use of enclosures – only exposing what is necessary to the global namespace, while the bulk of the internal workings are safely hidden away where no other scripts running on the same page can get at them. There’s a good introduction to tutorials in this excerpt from “Secrets of the Javascript Ninjas” – http://mpathirage.com/files/javascript_ninja/JavaScriptNinja_ch3_Article2.pdf

    Here’s the language construct you need to familiarize yourself with to do encapsulation:

    var myNamespace = (function(){ // assign the return value of an anonymous function to a var in the global space
    function myNamespace(){
    // Initialize
    }
    var hiddenStuff = “my secret”; // anything you define here will be hidden from the global scope.
    return myNamespace;
    })();

    As for polymorphic inheritance, it is actually easy to inherit from an object, and override a parent method.

    Parent = function() {
    // bunch of properties
    }
    Parent.someMethod = function () {
    // some behavior to override
    }

    var parentObj = new Parent();
    var childObj = Object.create(parentObj);
    childObj.someMethod = function () {
    // new behavior for child
    }

    Of course, you can also do all this within the child object’s constructor, and then just do:

    var childObj = new ChildObj();

    When you call childObj.someMethod(); you’ll get the child version, not the parent’s prototype version.

    Javascript is certainly a different way of working, but once you wrap your brain around prototypical inheritance, you’ll see that:

    1) Javascript can mimic class-based inheritance models, complete with encapsulation and polymorphic inheritance.

    2) Prototypical inheritance is actually less verbose and more expressive than class-based inheritance, and…

    3) Class-based inheritance cannot easily mimic prototypical inheritance.

    In other words – Javascript has BETTER OO than C++ and Java.

    If you want to criticize Javascript, there are plenty of valid attacks you can make – for example, Javascript lacks fast matrix manipulation capabilities, because it lacks support for predictable array element lengths (array elements with strong types). It also only supports one number type, (IEEE float), and that number type sucks for doing even basic floating point math.

    Until these REAL problems are fixed, we’re never going to see, for example, a high-performance 3D game engine written in Javascript running in the browser. (Although there are people doing 2 1/2 D game engines similar to the original Doom engine even with these limitations).

  1. 1 The Main Reason For JavaScript Unreadability at engfer(s)