5

Can anyone point me in the right direction of some real world object-orientated javascript? I'm learning OO for javascript from a few books but all the examples given in these books boil down to the dog object inheriting from the animal prototype or similar. I really want to see something a bit more substantial.

I've looked at jQuery and similar libraries (base, prototype) but I consider them to be verbose examples. I was looking for a script where I can see inheritance in use (classical or protoypal) clearly.

2 Answers 2

5

Good "real world" examples to learn OO javascript is to actually study some of the javascript frameworks out there. Some of them support and use OO within their own framework code:

These provide great reference and various strategies for writing OO javascript.

3
  • Hi- thanks for the reply. Just downloaded YUI and compared to looking at the jQuery library code it's very clear how the library is working...I can see Crockfords object() function for inheritance in there as well Aug 8, 2010 at 17:17
  • @elduderino I learned a lot from YUI looking early versions yui too. All these frameworks are great to study some neat tricks in javascript! And doug Corckford's links on javascript are gold!
    – naikus
    Aug 8, 2010 at 17:27
  • +1: This is really good advice. I'm learning Javascript OO right now and I downloaded all of the above to use as a reference library. Jul 11, 2011 at 1:51
2

IMO, javascript's prototype thingie is very useful, and classic OOP is not necessary.

As a real-world example, consider the google maps v3 api. Let's implement a new OverlayView:

// implement an OverlayView //
MyOverlay.prototype = new google.maps.OverlayView();

// the "constructor" function // function MyOverlay(position, node, map) { // set the parameters // this.position = position; this.node = node; this.map = map; this.setMap(this.map); }

// required onAdd function // MyOverlay.prototype.onAdd = function() { // observe the getPanes function inherited from OverlayView // var panes = this.getPanes(); // bla bla // }

// required draw function // MyOverlay.prototype.draw = function() { // bla bla // } // .. other functions //

// now instantiate an object // var instance = new MyOverlay(position, node, map);

If this doesn't work for you, many external libraries (e.g. Prototype, dojo, jquery, etc) offer great solutions for classic OOP.

1
  • Yeah that works for me. The concepts prototype, pseudo-classical and prototypal are clear to me but I'm just having problems seeing how to introduce it in to my own code. Aug 8, 2010 at 17:19

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.