Is JavaScript object-oriented?

IMO (and it is only an opinion) the key characteristic of an object orientated language would be that it would support polymorphism. Pretty much all dynamic languages do that.

The next characteristic would be encapsulation and that is pretty easy to do in Javascript also.

However in the minds of many it is inheritance (specifically implementation inheritance) which would tip the balance as to whether a language qualifies to be called object oriented.

Javascript does provide a fairly easy means to inherit implementation via prototyping but this is at the expense of encapsulation.

So if your criteria for object orientation is the classic threesome of polymorphism, encapsulation and inheritance then Javascript doesn’t pass.

Edit: The supplementary question is raised “how does prototypal inheritance sacrifice encapsulation?” Consider this example of a non-prototypal approach:-

function MyClass() {
    var _value = 1;
    this.getValue = function() { return _value; }
}

The _value attribute is encapsulated, it cannot be modified directly by external code. We might add a mutator to the class to modify it in a way entirely controlled by code that is part of the class. Now consider a prototypal approach to the same class:-

function MyClass() {
  var _value = 1;
}
MyClass.prototype.getValue = function() { return _value; }

Well this is broken. Since the function assigned to getValue is no longer in scope with _value it can’t access it. We would need to promote _value to an attribute of this but that would make it accessable outside of the control of code written for the class, hence encapsulation is broken.

Despite this my vote still remains that Javascript is object oriented. Why? Because given an OOD I can implement it in Javascript.

Leave a Comment