55

There have been some questions about whether or not JavaScript is an object-oriented language. Even a statement, "just because a language has objects doesn't make it OO."

Is JavaScript an object-oriented language?

Gabi Purcaru
  • 30,940
  • 9
  • 79
  • 95
ScottKoon
  • 3,483
  • 6
  • 27
  • 29
  • i would add the "subjective" tag – Sklivvz Sep 20 '08 at 07:21
  • 2
    I don't think this is subjective. It either is or it isn't or there is a specific reason for it being in the middle. Why do you think it is subjective? – Eric Schoonover Sep 20 '08 at 07:26
  • This question had 11 answers within 34 seconds of being posted - wow. – micahwittman Sep 20 '08 at 08:44
  • 4
    Because the definition of "object-oriented" does not specify a series of criteria to determine an exact answer – Sklivvz Sep 20 '08 at 14:00
  • 1
    I agree with Sklivvz this is subjective since the there is no authority specifying exactly what characteristics a language must have to be have the adjective 'object-oriented'. – AnthonyWJones Sep 20 '08 at 16:46
  • is there a way to refine the question? – ScottKoon Sep 21 '08 at 02:59
  • Interestingly, most of the folks who answer 'no, it is not' do so claiming JS lacks code reuse through inheritance, which is probably one of the _worst_ features of traditional OO languages, and one we can and should do without. – KaptajnKold Mar 17 '11 at 14:26
  • More-so an opinion rather than an answer, but here's my two cents. Sure JS may be OO, but it lacks a couple things that I think are very characteristic of OO languages. 1. Classes. They help you stay organized by forcing you to encapsulate your program. 2. Required declarations. Sure this may seem annoying, but yet again, it forces you to stay organized. – rshea0 May 23 '12 at 05:02
  • Yes! Much like how skateboards and unicycles can be called "travel oriented vehicles". – Jeff Austin Jun 22 '12 at 01:50

27 Answers27

53

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.

hippietrail
  • 15,848
  • 18
  • 99
  • 158
AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
  • 3
    How does prototypal inheritance sacrifice encapsulation? – ScottKoon Sep 21 '08 at 03:06
  • 1
    Encapusation requires storing private data on the execution context created when constructing the object. Members added to the prototype do not have access to this execution context and hence can not access the encapsulated data. – AnthonyWJones Sep 21 '08 at 12:03
  • The example given does not compile in C# either, so would you say that it is not object oriented? public class MyClass : ParentClass { private int _value = 1; } public class ParentClass { public int GetValue() { return _value; } } – liammclennan Oct 29 '09 at 21:44
  • @liammclennan? I'm not sure what you are driving at? C# is clearly an object oriented. I'm not sure what point is served by attempting to port the Javascript code in my example to C# which is an incomplete port because it doesn't compile. – AnthonyWJones Oct 29 '09 at 22:16
  • @AnthonyWJones liammclennan is correct. The code presented in the answer would translate to public MyClass { private int _value = 1; public static GetValue () { return _value; } } which does not compile. You cannot access an instance variable(non-static) from a class(static) method. Ruby has a similar limitation. – Thedric Walker Jan 05 '10 at 16:15
  • @Thedric: I can see why it would be broken in C#, it is also broken in Javascript, thats the __point__ of the example. I still can't see why porting it to C# is useful to the discussion though, the discussion is squarely about Javascript not C# or ruby. BTW the port as you have it isn't equivalent, you can't even call your `GetValue` against an __instance__ of `MyClass` anyway, in my code the `getValue` is not equivalent to a static method, a closer equivalent would be an extension method in C#. – AnthonyWJones Jan 19 '10 at 11:12
  • 2
    You are right that the C# is not necessary and that I missed the point. However, the point should have been this. Encapsulation does not equal information hiding. IH is a concept that is associated with encapsulation. And information hiding is what you edit hints at. Encapsulation is more conceptual than that. It refers to what the outside world uses to interact with an object. Thus Scott Koon's question. – Thedric Walker Jan 19 '10 at 19:53
  • @Thedric: In the current context I don't see the need to make such a distinction. Yes "Encapsulation" is a wider term but its only in its application to information held inside an object that its interesting from an OO perspective, after all, every function ever written in all of history is an excercise in encapsulating logic whether its a non-OO procedure or method on an object. – AnthonyWJones Jan 19 '10 at 20:32
  • But according to the definition of encapsulation that you are using then any language that supports public fields can have their object-orientation called into question. – Thedric Walker Jan 20 '10 at 19:48
  • @Thedric: No just because a language __can__ expose a public field doen't disqualify it in most peoples assessment. The main thrust of my answer is that plain Javascript doesn't support both private fields __and__ implementation inheritance __simulatenously__. For many this would be a disqualifying limitation not that I personnally subscribe to that point of view. – AnthonyWJones Jan 20 '10 at 21:23
  • 6
    For the record, JavaScript is not unique in this regard. Python also has no mechanism to enforce encapsulation. All members of a Python object are effectively public, and Python only uses naming conventions to indicate that a member should be treated as "private". But no one questions whether or not Python is an OO language. – Daniel Pryden May 14 '10 at 17:28
  • @Casebash: I'm not sure what your question is? – AnthonyWJones Aug 27 '10 at 06:57
  • @Anthony: Deleted my comment, I didn't read your answer carefully enough – Casebash Aug 27 '10 at 23:06
  • 2
    A much truer-to-the-root definition of OO would be based on "message passing"; in any OO language, the primary design methodology is "objects passing messages to other objects" instead of "accessing and modifying fields". Method calling is one popular form of message passing. Polymorphism and inheritance is not an inherent property of OO, they are only necessary due to limitations imposed by static typing; encapsulation is inherent in a message passing system (because you never access variables directly, you just send messages to other objects), but it's not the main focus of OO. – Lie Ryan Oct 30 '10 at 19:17
  • JavaScript has information hiding with privileged functions: http://www.crockford.com/javascript/private.html – Amir Moghimi Jan 07 '11 at 07:13
  • @Amir: Yes that works nicely but you can't use the prototypal form of inheritance with that approach. There are other approaches to implementing inheritance that uses this closure approach but one would have to question whether its the developer writing an OO framework rather Javascript being OO. – AnthonyWJones Jan 07 '11 at 08:26
  • @Lie: I would agree that inheritance is a later addition to the original message passing root of early object oriented development. However polymorphism __is__ inherent in the older message passing world, very different objects can accept a sub-set of common messages. I would also disagree that encapsulation "is the main focus of OO", it may have been in the past but its the polymorphic nature of OO that really gives value. The re-use of __calling__ code that can be applied to a super-type (or later an interface) is today every bit as valuable (if not more valuable) as encapsulation. – AnthonyWJones Jan 07 '11 at 08:45
  • @AnthonyWJones: Polymorphism is only important in OOP that uses static typing. The concept of data types does not really need to exist as a language construct of an OOP language; type can be implicitly understood as whatever messages the object can sensibly send and/or receive. OOP is centered around the concept of passing messages. I agree, encapsulation was never the main focus of OO, except recently by those that apparently misunderstood a particular implementation of OOP as OOP itself. – Lie Ryan Jan 07 '11 at 18:40
  • @Lie: "type can be implicitly understood as whatever messages the object can sensibly send and/or receive". Indeed this is the very essence of polymorphism, static typing has nothing to do with it. An object can be considered to be of a type because it understands a specific set of messages, it may understand other sets of messages giving it effectively multiple types, it is __polymorphic__. Polymorphism is not limited to static typing it is just much easier to do dynamically, so easy that you don't need to think about and the concept gets lost but we are actually doing it a lot. – AnthonyWJones Jan 07 '11 at 19:59
  • Uh... `function MyClass() { var _value = 1; MyClass.prototype.getValue = function() { return _value; } }` – eyelidlessness Jul 10 '11 at 06:47
  • @eyelidlessness: Your code is very broken, or was that the point you were trying to make? Try adding a `incrementValue` method and then play around with multiple instances of MyClass and you'll see what I mean. – AnthonyWJones Jul 11 '11 at 12:08
  • Can you be more specific? Adding `incrementValue` to the `prototype` in the constructor body the same way `getValue` was added behaves as expected... each instance begins with `_value == 1` and `incrementValue` increments `_value` for that instance only, just as a `private` property would behave in a class. What is the behavior you expect? What am I missing? http://jsfiddle.net/7ag7Z/ – eyelidlessness Jul 11 '11 at 17:55
  • @eyelidlessness: You are missing the fact that there is only __one__ prototype object. Hence __all__ instances `MyClass` will share the exact same functions as the last instance to be created. If you create two instances then call increment on both, then call getValue on both, you will get 3 returned by both. The functions that were created in the first instance are discarded and replaced when you create the second instance. The execution scope of the first is no longer in use, even by the the first instance because the functions it exposes are now actually the ones created in the second. – AnthonyWJones Jul 13 '11 at 12:25
  • @Anthony, you're right. It's still resolvable. See my revision: http://jsfiddle.net/7ag7Z/1/ – eyelidlessness Jul 13 '11 at 17:48
  • @eyelidlessness: Your code may work but it makes the use of prototype pointless. The whole point of the prototype is to allow single set of properties/methods to be shared by multiple instances of a "class". In your code you now have individual functions for each instance, you might a well have used the first example code in my answer. – AnthonyWJones Jul 14 '11 at 12:38
36

The short answer is Yes. For more information:

From Wikipedia:

JavaScript is heavily object-based. Objects are associative arrays, augmented with prototypes (see below). Object property names are associative array keys: obj.x = 10 and obj["x"] = 10 are equivalent, the dot notation being merely syntactic sugar. Properties and their values can be added, changed, or deleted at run-time. The properties of an object can also be enumerated via a for...in loop.

Also, see this series of articles about OOP with Javascript.

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
24

Javascript is a multi-paradigm language that supports procedural, object-oriented (prototype-based) and functional programming styles.

Here is an article discussing how to do OO in Javascript.

jop
  • 82,837
  • 10
  • 55
  • 52
19

Languages do not need to behave exactly like Java to be object-oriented. Everything in Javascript is an object; compare to C++ or earlier Java, which are widely considered object-oriented to some degree but still based on primitives. Polymorphism is a non-issue in Javascript, as it doesn't much care about types at all. The only core OO feature not directly supported by the syntax is inheritance, but that can easily be implemented however the programmer wants using prototypes: here is one such example.

Eevee
  • 47,412
  • 11
  • 95
  • 127
  • A nitpick: Javascript has primitive values as well, and they are not objects. Undefined, null, boolean, number, and string, to be spesific. – Internet Friend Sep 20 '08 at 07:43
  • I know Javascript has primitive types, but I don't really consider them such in the usual sense because they still *act* like objects (except those that explicitly mean "nothing"). typeof("foo") gives you 'string' rather than 'object', yes, but strings still have methods; "foo".substr(1) works. – Eevee Sep 20 '08 at 07:51
  • Ha, I don't mean to be inciting wars, just comparing to a language that is nearly universally considered OO. Perhaps I should clarify that a bit. – Eevee Sep 20 '08 at 08:08
  • I removed my comment as it's no longer relevant. Disperse please, nothing to see here :) – Internet Friend Sep 20 '08 at 08:14
  • 1
    @InternetFriend - typeof(null) = 'object', boolean, number and string are all classes extending object, undefined is never a value, it is by definition the absence of a value and *where it itself is defined* it's as a property – annakata Dec 28 '08 at 21:42
  • @OP - JS supports inheritance in the form of prototyping – annakata Dec 28 '08 at 21:43
  • "Polymorphism is a non-issue in Javascript" This is very wrong! myObj.talk() will mean different things depending on what myObj has in its "talk" slot. This has nothing to do with JS being dynamically typed. – interstar Jan 03 '09 at 00:45
  • I thought that everything in Javascript is an associative array. – David Alpert Oct 29 '09 at 21:45
10

JavaScript is object-oriented, but is not a class-based object-oriented language like Java, C++, C#, etc. Class-based OOP languages are a subset of the larger family of OOP languages which also include prototype-based languages like JavaScript and Self.

munificent
  • 11,946
  • 2
  • 38
  • 55
10

Yes and no.

JavaScript is, as Douglas Crockford puts it, "the world's most misunderstood programming language." He has some great articles on JavaScript that I'd strongly recommend reading on what exactly JavaScript is. It has more in common with LISP that C++.

David Mohundro
  • 11,922
  • 5
  • 40
  • 44
8

JavaScript is a prototype-based programming language (probably prototype-based scripting language is more correct definition). It employs cloning and not inheritance. A prototype-based programming language is a style of object-oriented programming without classes. While object-oriented programming languages encourages development focus on taxonomy and relationships, prototype-based programming languages encourages to focus on behavior first and then later classify.

The term “object-oriented” was coined by Alan Kay in 1967, who explains it in 2003 to mean

only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things. (source)

In object-oriented programming, each object is capable of receiving messages, processing data, and sending messages to other objects.

For a language to be object-oriented in may include features as encapsulation, modularity, polymorphism, and inheritance, but it is not a requirement. Object-oriented programming languages that make use of classes are often referred to as classed-based programming languages, but it is by no means a must to make use of classes to be object-oriented.

JavaScript uses prototypes to define object properties, including methods and inheritance.

Conclusion: JavaScript IS object-oriented.

elixenide
  • 44,308
  • 16
  • 74
  • 100
  • I suspect only a few of us are old enough to remember that definition of Object Oriented. I remember delivering an OOD using VAX BASIC something like 20 years ago. – AnthonyWJones Sep 30 '08 at 21:14
6

Unlike most object-oriented languages, JavaScript (before ECMA 262 Edition 4, anyway) has no concept of classes, but prototypes. As such, it is indeed somewhat subjective whether to call it object-oriented or not.

@eliben: Wikipedia says object-based. That's not the same as object-oriented. In fact, their article on object-based distinguishes between object-oriented languages and prototype-based ones, explicitly calling JavaScript not object-oriented.

Sören Kuklau
  • 19,454
  • 7
  • 52
  • 86
  • However if you read the supplementary article on object-based languages it is noted that Javascript is a object-oriented language, albeit a prototype-based one. The only example that is given of an object based language is the now mostly deprecated VisualBasic. – Thedric Walker Jan 05 '10 at 16:30
3

JavaScript is a very good language to write object oriented web apps. It can support OOP because supports inheritance through prototyping also properties and methods. You can have polymorphism, encapsulation and many sub-classing paradigms.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
2

This is of course subjective and an academic question. Some people argue whether an OO language has to implement classes and inheritance, others write programs that change your life. ;-)

(But really, why should an OO language have to implement classes? I'd think objects were the key components. How you create and then use them is another matter.)

Christian Davén
  • 16,713
  • 12
  • 64
  • 77
2

it is a good thread. Here's some resources i like. Most people start out with prototype, jquery, or one of the top 6 libs(mootools, ExtJS, YUI), which have different object models. Prototype tries to replicate classical O-O as most people think of it

http://jquery.com/blog/2006/08/20/why-jquerys-philosophy-is-better/

Here's a picture of prototypes and functions that i refer to a lot

http://www.mollypages.org/misc/js.mp?

Gene T
  • 5,156
  • 1
  • 24
  • 24
2

I am responding this question bounced from another angle.

This is an eternal topic, and we could open a flame war in a lot of forums.

When people assert that JavaScript is an OO programming language because they can use OOD with this, then I ask: Why is not C an OO programming language? Repeat, you can use OOD with C and if you said that C is an OO programming language everybody will said you that you are crazy.

We could put here a lot of references about this topic in very old books and forums, because this topic is older than the Internet :)

JavaScript has not changed for many years, but new programmers want to show JavaScript is an OO programming language. Why? JavaScript is a powerful language, but is not an OO programming language.

An OO programming language must have objects, method, property, classes, encapsulation, aggregation, inheritance and polymorphism. You could implement all this points, but JavaScript has not them.

An very illustrate example: In chapter 6 of "Object-Oriented JavaScript" describe 10 manners to implement "inheritance". How many manners there are in Java? One, and in C++? One, and in Delphi (Object Pascal)? One, and in Objective-C? One.

Why is this different? Because Java, C++, Delphi and Objective-C are designed with OOP in mind, but not JavaScript.

When I was a student (in 1993), in university, there was a typical home work: Implement a program designed using a OOD (Object-oriented design) with a non-OO language. In those times, the language selected was C (not C++). The objective of this practices was to make clear the difference between OOD and OOP, and could differentiate between OOP and non-OOP languages.

Anyway, it is evidence that not all people have some opinion about this topic :)

Anyway, in my opinion, JavaScript is a powerful language and the future in the client side layer!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
angelcervera
  • 3,699
  • 1
  • 40
  • 68
1

Hanselminutes episode 146 looks at OO Ajax. It was a good show and definitely a good show to help form an opinion.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aaron Powell
  • 24,927
  • 18
  • 98
  • 150
  • Honestly, that show perpetuated several mischaracterizations about JavaScript and was the reason I asked this question here. I wanted a place I could point to the next time someone made the claim that JavaScript isn't object oriented. – ScottKoon Sep 21 '08 at 02:55
1

Misko Hevery did an excellent introductory Google Tech Talk where he talks about objects in Javascript. I've found this to be a good starting point for people either questioning the use of objects in Javascript, or wanting to get started with them:

rodrigo-silveira
  • 12,607
  • 11
  • 69
  • 123
0

For me personally the main attraction of OOP programming is the ability to have self-contained classes with unexposed (private) inner workings.

What confuses me to no end in Javascript is that you can't even use function names, because you run the risk of having that same function name somewhere else in any of the external libraries that you're using.

Even though some very smart people have found workarounds for this, isn't it weird that Javascript in its purest form requires you to create code that is highly unreadable?

The beauty of OOP is that you can spend your time thinking about your app's logic, without having to worry about syntax.

Kokodoko
  • 26,167
  • 33
  • 120
  • 197
0

Is JavaScript object-oriented?

Answer : Yes

It has objects which can contain data and methods that act upon that data. Objects can contain other objects.

  • It does not have classes, but it does have constructors which do what classes do, including acting as containers for class variables and methods.
  • It does not have class-oriented inheritance, but it does have prototype-oriented inheritance.

The two main ways of building up object systems are by inheritance (is-a) and by aggregation (has-a). JavaScript does both, but its dynamic nature allows it to excel at aggregation.

Some argue that JavaScript is not truly object oriented because it does not provide information hiding. That is, objects cannot have private variables and private methods: All members are public.

But it turns out that JavaScript objects can have private variables and private methods. (Click here now to find out how.) Of course, few understand this because JavaScript is the world's most misunderstood programming language.

Some argue that JavaScript is not truly object oriented because it does not provide inheritance. But it turns out that JavaScript supports not only classical inheritance, but other code reuse patterns as well.

Sources : http://javascript.crockford.com/javascript.html

Community
  • 1
  • 1
Vinayak Bevinakatti
  • 40,205
  • 25
  • 108
  • 139
0

The Microsoft Ajax Client Library makes it simple to implement OO in javascript. It supports inharitence, and interface implementation.

urini
  • 32,483
  • 14
  • 40
  • 37
0

I think a lot of people answer this question "no" because JavaScript does not implement classes, in the traditional OO sense. Unfortunately (IMHO), that is coming in ECMAScript 4. Until then, viva la prototype! :-)

Andrew Hedges
  • 21,688
  • 16
  • 67
  • 79
0

I think when you can follow the same or similar design patterns as a true OO language like Java/C#, you can pretty much call it an OO language. Some aspects are obviously different but you can still use very well established OO design pattersn.

mattlant
  • 15,384
  • 4
  • 34
  • 44
0

JavaScript is Object-Based, not Object-Oriented. The difference is that Object-Based languages don't support proper inheritance, whereas Object-Oriented ones do.

There is a way to achieve 'normal' inheritance in JavaScript (Reference here), but the basic model is based on prototyping.

dsm
  • 10,263
  • 1
  • 38
  • 72
0

Everything in javascript is an object - classes are objects, functions are objects, numbers are objects, objects objects objects. It's not as strict about typing as other languages, but it's definitely possible to write OOP JS.

matt lohkamp
  • 2,174
  • 3
  • 28
  • 47
0

Yes, it is. However, it doesn't support all of the features one would expect in an object oriented programming language lacking inheritance and polymorphism. This doesn't mean, however, that you cannot simulate these capabilities through the prototyping system that is avaialble to the language.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MikeJ
  • 14,430
  • 21
  • 71
  • 87
0

Javascript is not an object oriented language as typically considered, mainly due to lack of true inheritance, DUCK typing allows for a semi-true form of inheritance/polymorphism along with the Object.prototype allowing for complex function sharing. At its heart however the lack of inheritance leads to a weak polymorphism to take place since the DUCK typing will insist some object with the same attribute names are an instance of an Object which they were not intended to be used as. Thus adding attributes to random object transforms their type's base in a manner of speaking.

bmeck
  • 426
  • 2
  • 4
0

Technically it is a prototype language, but it's easy to to OO in it.

Rik
  • 28,507
  • 14
  • 48
  • 67
0

It is object oriented, but not based on classes, it's based on prototypes.

Vasil
  • 36,468
  • 26
  • 90
  • 114
0

Objects in JavaScript inherit directly from objects. What can be more object oriented?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pavel Feldman
  • 4,621
  • 7
  • 30
  • 31
-1

I would say it has capabilities to seem OO. Especially if you take advantage of it's ability to create methods on an existing object (anonymous methods in some languages). Client script libraries like jquery (jquery.com) or prototype (prototypejs.org) are good examples of libraries taking advantage of this, making javascript behave pretty OO-like.

Per Hornshøj-Schierbeck
  • 15,097
  • 21
  • 80
  • 101
  • 2
    Why do people think classical OOP is the only true form of OOP. *facepalm* – Zach Sep 20 '08 at 19:15
  • when was there such a thing as classical OOP. What's the new OOP then...moshing to the tunes of Metallica not having a clue what's going on but having a real good time?....sorry....I am very very tied....:) – WeNeedAnswers Jan 20 '12 at 05:48