tags:

views:

740

answers:

12

This might come as a strange question to many of you, and I don't actually know if it is correct to say OOP in this context, because OOP (object-oriented programming) is usually associated with programming languages like C++ and Java, and not lightweight programming languages, or scripting languages. My question, however, is in the category of JavaScript, which is also object oriented. I do know about objects, properties, methods, prototypes and constructors, I just can't seem to get into my mind when to use objects.

When I am writing my web-applications, I, for some reason, never use objects. This annoys me, because when I read about objects in a variety of books and online articles, objects make everything so much simpler and, just to put it out there, I HATE repeating myself, and this is why I wish I knew when to use objects.

I really want to become better at using objects and when to use objects.

Can you please mention a few situations objects would be good? It would be really nice to have written down something you know you can go back and look at when you get confused about when to use these darn objects :)

I would love simple answers explaining why and when objects are to prefer.
I would also like if you could tell me if I am to use objects when I am in some special situations generally suitable for objects i.e. every time you want to ___ then you use an object...


I really hope you understand my question and you will consider that I'm somewhat new to this site and new to JavaScript

Thanks!

+11  A: 

You probably use objects without even realizing it.

If you're writing Javascript that interacts with the DOM, you're using objects.

If you're using any of the Javascript frameworks out there (jQuery, MooTools, etc.), you're using objects.

Using objects will be useful when you need to encapsulate some commonly used code so that it can be easily re-used (within a single application or across multiple applications like jQuery plugins...which are objects in and of themselves).

And to answer the question in the title of your post...the only way to really get better at OOP is to practice! Reading and studying the subject can only get you so far.

Justin Niessner
@Marcel - Good catch. Apparently I was on autopilot this morning. Fixed.
Justin Niessner
@Justin, *using* objects is nothing like actually implementing object oriented code. Any programmer can create and object and call a method on it, writing decent OO code is much harder.
Ash
+8  A: 

The first thing to remember, is that a lot of simple Javascript code really doesn't need to define objects (using them is inevitable, as all the stuff the DOM gives you are objects). Don't panic too much.

One of the good things about Javascript is that it supports a lot of different styles; OOP, imperative and functional.

One of the bad things about using Javascript is that because it supports a lot of different styles, it's hard to learn another style, at least until you are forced to an "a-ha" moment by something else.

Spending time in languages that are more inclined to force you into OOP (even when some would argue they shouldn't) is helpful here. C# and Java force one along OOP lines, though C++ does not (with the same strength and weakness here as with Javascript).

Try to think about the "things" in your program. Some of these things will already be modelled by objects (those the DOM gives you). Some really will just be numbers and strings and not worth composing beyond that (though learning how to add functionality to those types through prototype is a good idea too). Some will be "things" more complicated than a simple type and naturally suited to modelling as an object.

Do also look at functional programming in Javascript (e.g. passing a function as a parameter to another function is about the simplest example), as the interaction between this and OOP is one of the strongest elements in Javascript, and essential in defining methods on objects given the prototype-based OOP model it has.

Jon Hanna
While C++ might not force you to use OOP, it does not carry the exact same disadvantages as javascript. The key here is that in C++, the "correct" (and recommended) way is OOP, while in javascript it is just another style, with clumsy syntax. The differences are similar but not the same.
Jasper
@Jasper, yes though in terms of learning, it depends on how you learn. If you learn C++ by learning C and then learning that C++ lets you add other stuff, it can be easy to end up writing C in C++. Contrarily, if you learn Javascript by being taught about objects very early on, it can be easier to think of it in OOP terms (perhaps too easy, sometimes it's good that you can take an imperative approach).
Jon Hanna
@Jon Hanna: That's true, there is a wrong way of learning C++ and it's the logical way to learn C++ if you learn(ed) C first. However, there are many examples of books or websites allowing you to learn proper C++. At the same time, there is no such thing as "wrong" and "right" ways to learn javascript. While I agree with you most of the way, I would not dis-recommend C++ as a language to learn OOP for the reason it has other capabilities (while I just did that for javascript). Nevertheless, there are probably other reasons not to start off with C++ anyway...
Jasper
@Jasper, I'm certainly not disrecommending C++ as a language to learn OOP with. Any good guide that starts from scratch with the language will teach someone well, but then so will any good book on JS (though it may focus more on functional). The disadvantage I'm speaking off is purely a matter of what bad ways you can use it. Often the bad ways of using a language are more visible differences between them than the good ways!
Jon Hanna
@Jon Hanna: My bad then... I guess that it's just that I would disrecommend javascript for learning OOP, mainly because I believe there to be a plethora of things you don't want to do in OOP in javascript - whereas in C++ you want to do everything in OOP, with an occasional exception.
Jasper
@Jasper, I probably came across as disrecommending C++ because I was solely looking at one negative aspect of how it is sometimes taught in talking about it. I agree that JS wouldn't be my first choice in teaching OOP.
Jon Hanna
+2  A: 

Javascript is just a terrible language to learn OOP in. I would recommend learning OOP in another language (like Java or C++) and then learn Object Oriented syntax in Javascript. At that moment you have all the ingredients.

That's when you can decide whether or not you want to be using an object for a task in Javascript or if it is enough to use just functions.

Personally, I mostly write non-object javascript and leave objects for when a task feels object oriented to me. For example, I used an object oriented design for a drag and drop script, in which you simply made a DragNDrop object with the correct parameters and the items in your page would be dragable from that moment on, or when I wanted to simplify some javascript xml handling functions, I wrote an object that wrapped the normal xml objects.

Jasper
@Marcel Korpel: I didn't say javascript is terrible - it's actually a pretty nice language. I did say (somewhere else on this page) that javascript's OO syntax is clumsy. I only said it is a terrible place to start learning OOP.
Jasper
I disagree with that, but I already left a comment on your answer explaining why I don't agree, so I am not going to do the same thing here again.
Jasper
A: 

Javascript is much, much less object oriented than C# or Java; don't worry if your Javascript doesn't look object oriented.

Dean J
Just curious, where'd this idea come from?
indieinvader
Object orientation is conceptual and acutally go hand-in-hand with design. There are certain unrefuted characteristic of good design that can be achieved with any programming language that supports some sort of object model. Heck, it is even possible to exhibit good OOP and design with VB6 (albeit, with a little bit of creativity)
SideFX
You can write purely imperative, non-OOP scripts in Javascript. You can't do that in Java; it simply doesn't work, as everything is in a class. I'll stick by my guns on this one, downvote or no. Javascript isn't often going to look much like Java, and that's a good thing.
Dean J
@SideFX; I'd agree, but that doesn't mean you should force all VB6 code into OOP, should you?
Dean J
@indieinvader; glad to give a specific response if you can give a more specific question; see my first response as a comment, let me know if that covers it?
Dean J
+3  A: 

My personal experience with OOP in JavaScript is a positive one, once I figured out to get it to do what I wanted of course, I usually use it in combination with jQuery so the resulting code can seem a bit.... odd.

function BlogPost(id,title,content)
{
    this.id = id;
    this.title = title;
    this.content = content;

    function display()
    {
        var post = $('<div class="blogpost"></div>');
        $(post).append('<h2>' + this.title + '</h2>');
        $(post).append('<p>' + this.content + '</p>');
        var deleteButton = $('<span class="deletePost">delete</span>')
        $(post).append(deleteButton);
        $(deleteButton).click(this.delete)

        $('#postcontainer').append(post);
    }


    function delete()
    {
        $.post('some/xhr/handeler',{id:this.id});
    }
}

This is a quick (untested) class that can be used to dynamically add blogposts to a div with id postcontainer' and handles clicks on a delete button.

Kristoffer S Hansen
+7  A: 

First, you don't need to use objects to avoid repeating yourself. If you need to do the same thing at two points in your code, you can write a plain vanilla non-OOP function to do that and call it twice.

To summarize the advantages of OOP without writing a book here, OOP basically does three things for you:

  1. Group related data together. Non-OOP programs often have a whole bunch of variables floating around in the main program that are only loosely related. With OOP, you put related variables into an object.

  2. Associate functions with data. By putting functions in an object with the data they operate on (purists will say they are then "members" rather than "functions"), you make it clear to the reader that these go together.

Combining #1 and #2 lets you hide implementation details from other objects. You create the "public interface" for a class, the set of functions that other objects should call and that represent the logical things that this class does, and then any other functions you need can be hidden. (More explicitly in some languages than in others, but that's not the point here.)

  1. Classes can inherit and mutate. If you have two similar classes A and B that should be mostly the same but with some minor differences, you can make a superclass C with all the common stuff and then A and B inherit from that and each adds in its own unique stuff. This is what is usually advertised as the power of OOP. Frankly, yes, it's way cool, and in some situations can be very handy, but I only use its true power occasionally, and I suspect the same is true of most programmers. (OOP enthusiasts feel free to jump in with how and why you use inheritance all the time.)

When to OOP it? Any time you have several pieces of data that logically go together, it makes sense to create a class to hold them. Like X and Y coordinates; or customer name, address, and zip code; or phaser range and phaser power consumption; or whatever.

Any time you have functions that logically operate on this related data, put them in the the class with the data. Like "capitalize customer name", "compute distance of this point from the origin", etc.

How and when to use inheritance is more complicated. I'll leave that for another time.

Jay
This is the best answer so far. It actually answers the question.
San Jacinto
+2  A: 

Think about how you can use objects to organize and simplify your application. I have found two metaphors useful:

  • A mechanical watch is made up of a number of gears, each of which serves a single purpose in the overall operation of the machine. If you think of your application as a watch, then objects are its gears.

  • A workgroup is made up of a number of people, each of whom performs a specific job. The people communicate with each other in performing their jobs, and the jobs fall along two lines--those that perform tasks (workers), and those that organize and direct the work of other people (managers).

You can use these metaphors to organize the work your application does. Start by dividing the app into functional layers; UI, business layer, and persistence, for example. Take each of your use cases, and distribute the work it does among these layers. That should give you a starting point for the classes you will need.

Make each class as self-contained a possible. you want to seal it off when it is done, like a .NET control. Classes should communicate with each other only through their interfaces, which are made up of properties and methods. These interfaces should have the smallest footprint (fewest public properties and methods) you can come up with. The idea is to isolate the side effects of a change to any class to that class alone.

If you do these things, you will be ahead of 80% of all programmers. You will find it much easier to develop and maintain even large applications, because you will be able to break complex problems down to simple components.

David Veeneman
+1  A: 

Justin Niessner said it and I can only add to his answer...

In addition to practice, I find reading other people's code very instructive. You need to be cautious because not all code is exemplary (to say the least) but developing critical skills is part of getting better.

fsb
+1  A: 

In my opinion I think it's better to think about OOP in the context of a particular domain or business problem. For example, JavaScript uses objects to model browser behavior and attributes, e.g., Window, Frame, History...

A domain model of a business problem will contain objects that will be reflected in the programming code written OOP. For example, a university student application will have objects for students, professors, courses, curriculums, rooms and so on. Consequently, begin with your business problem and model the domain. Your OOP code should have objects modeled from your domain. alt text

Source:http://csci.csusb.edu/dick/samples/uml0.html

johnnieb
+1  A: 

I think that using classes in general and OOP principles, makes your code neater, more readable and makes you more productive .

George
+1  A: 

You might be interested in design patterns (Book, Wikipedia), which tell you, how to solve common problems using OOP. Many classical design patterns may not be so relevant for JavaScript, since in JavaScript there are other non OOP elements (e.g. functions), which can solve some problems even more elegant.

Some simple design patterns I can recommend to start with:

  • Abstract factory: Defer the instantiation of objects. In JavaScript in most cases a function will do the job.
  • Decorator: Transparently add functionality to an object at runtime. Can also be nested. Usage example: Logging
  • Composite: Treat a tree/graph of object like a single object.
nang
Marcel Korpel
+1  A: 

Recently I worked on a web application that would require heavy client side Javascript.

Coming from C#/Java background I realized that Javascript would require a change of thinking, however I still wanted to apply good OO principles if possible, in particular to control the likely complexity of the application.

After a bit of searching I found a great book called Object Oriented Javascript by Stoyan Stefanov. It truly opened my eyes to power of this often called "toy language". Some sections on functional programming concepts, variable scoping and closures may even be a bit more advanced than you want.

However reading and applying many of these concepts from this book (closures, anonymous functions etc) in Javascript, has actually even helped me back in C# land where these concepts are only now becoming more mainstream.

Given your stated situation and goal I can highly recommend this book as one of the best ways to learn about doing OO in Javascript.

Ash