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.

6 thoughts on “JavaScript Is Not “Truly” Object Oriented

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

  2. > 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”?)

  3. 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

  4. 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).

  5. I wouldn’t go as far as to say that Javascript’s OO is better than that of C++, Java, etc. like Eric Hamilton did although I do prefer prototype-based OO better than class-based.

    The actual thing here I think people should keep in mind is that not even the world of OO is pure black and white. Although the mainstream OO community thinks that their dogma of OO is the only true way and that all other kinds of OO are simply just plain heresy that is not the whole truth of OO. To me someone talking about “true OO” just sounds like a someone arguing about who is a “true Christian”.

    According to OO experts (who see the big picture instead of just trying to market their own static and compiled class-based OO language) in the industry and academia it is simply not about what is “true OO” but about the fact that there is more than one way of doing OO which is why they don’t spend their time arguing if something is “truly OO” but instead they talk about the family tree of different kinds of OO models.

    There is more to OO than class-based OO. There is also prototype-based OO and probably some other less common models of OO as well. There is class-based inheritance, some languages uses delegation while others might just copy attibutes and methods around to achieve the same kind of behaviour on objects and then classify objects based on the kind of interfaces they can be inferred to support based on their available method names.

    Is Python truly OO? It doesn’t really enforce encapsulation. Still practically noone seems to have a problem calling it object-oriented. What is the point of having a dictionary if noone cares about what it says about what OO means? Then again Wikipedia is just wikipedia and hardly the final word on the subject.

    Which is why saying that “Javascript is not truly OO” at least to me sounds rather problematic. Javascript is OO. Its just not class-based OO. To me speaking about OO thinking that it by default is and can only mean the class-based variant of OO just sounds plain sloppy. Sorry.

    To me OO is more like a constantly moving and evolving target of various different modelling, design and coding techniques. Even aspect-oriented programming is usually implemented using OO techniques and used to augment OO as an extension of it. Which is why to me at least talk about what is “truly OO” just sounds like nitpicking. So to me OO is not a definition but more like a way of thinking, a philosophy or even a metaphilosophy. To me any language that allows me to think and to express myself with OO style is OO enough.

  6. “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?”

    Agreed, but why do you believe that the authoritative definition of “object orientation” is “encapsulation + polymorphic inheritance”? Says who?

    People use the term “object-oriented” to describe a whole range of programming paradigms. I think most people understand an “object” as a complex, user-definable data type that can comprise both state (properties) and functionality (methods). Yes, there clearly exists a classical version of OO to which encapsulation and polymorphism *are* integral. That doesn’t mean that classical OO is the One True OO.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>