tags:

views:

5292

answers:

25

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?

+28  A: 

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
+18  A: 

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
+1  A: 

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.

CMS
+17  A: 

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
A nitpick: Javascript has primitive values as well, and they are not objects. Undefined, null, boolean, number, and string, to be spesific.
Internet Friend
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
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
I removed my comment as it's no longer relevant. Disperse please, nothing to see here :)
Internet Friend
@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
@OP - JS supports inheritance in the form of prototyping
annakata
"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
I thought that everything in Javascript is an associative array.
David Alpert
A: 

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

urini
A: 

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
I guess that depends on which tradition your flavour of OO claims as its own.
Galghamon
A: 

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
Why do people think classical OOP is the only true form of OOP. *facepalm*
Zach
+1  A: 

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
+2  A: 

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
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
A: 

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
A: 

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
A: 

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
Javascript doesn't have classes
troelskn
What would you all the identifier on the right hand side of the new keyword?
AnthonyWJones
True, javascript doesn't have classes, fair enough - but the objects you make approximate classes, at least regarding how you interact with them.
matt lohkamp
Classes are a bookkeeping construct. Object do not neccessarily have anything to do with objects. IMHO what makes an object is the let over lambda.
Gutzofter
+1  A: 

A recent Hanselminutes (http://www.hanselminutes.com/default.aspx?showID=146) looks at OO AJAX, it was a good show and definately a good show to help form an opinion.

Slace
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
A: 

yes it is. however it doesnt support all of the features one would expect in an object oriented programming language lacking inheritence and polymorphism. this doesnt mean however that you cannot simulate these capabilities through the protyping system that is avaialble to the language.

MikeJ
+18  A: 

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.

AnthonyWJones
How does prototypal inheritance sacrifice encapsulation?
ScottKoon
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
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
@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
@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
@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
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
@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
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
@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
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
@Casebash: I'm not sure what your question is?
AnthonyWJones
@Anthony: Deleted my comment, I didn't read your answer carefully enough
Casebash
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
A: 

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
+7  A: 

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
A: 

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

Rik
A: 

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

Vasil
+4  A: 

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
+6  A: 

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.

Ódýr vefhýsing

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
A: 

Fun thread and thanks for all the input.

+1  A: 

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
A: 

Objects in javascript inherit directly from objects - wjat can be more object oriented?

Pavel Feldman
A: 

I am responding this question bounced from other one.

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

When people assert that JS is an OOP because they can use a OOD with this, then i ask: Why is not C an OOP? Repeat, you can use OOD with C and if you said that C is an OOP 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 internet :)

JS does not changed since years, but new programmers want sign JS as a OOP. Why? JS is a powerful language, but is not a OOP.

OOP must has 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 Obetive-C? One.

Why this different? Because Java, C++, Delphi and Obetive-C are designed with OOP in main, but JS no.

when i was student ( in 1993 ), in university, there was a typical home work: Implement a program designed using a OOD (Object-oriented design) with a not OOP language. In this times, the language selected was C (no C++). Objective of this practices was had a clear difference between OOD and OOP, and could difference between OOP and not OOP languages.

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

Anyway, in my opinion, JS is a powerful language and future on client side layer!

Apologies for my poor English.

angelcervera
Your concept of OOP is way, way too narrow and shaped by C++ and Java.
Michael Borgwardt
@michael It'is possible
angelcervera