Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

good example of OO JS?

Tags:

javascript

oop

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.

like image 779
Mike Rifgin Avatar asked Aug 08 '10 16:08

Mike Rifgin


People also ask

What is a good OO design?

Gamma's second principle of good OO design is to: Favor object composition over class inheritance. Systems that follow this rule have fewer classes and more objects. Their power is in the ways that the objects can interact with each other. It would be important to have good dynamic models.

What is OO in JavaScript?

Object-Oriented Programming is a way of writing code that allows you to create different objects from a common object. The common object is usually called a blueprint while the created objects are called instances. Each instance has properties that are not shared with other instances.

What are the 3 pillars of OO programming?

There are three major pillars on which object-oriented programming relies: encapsulation, inheritance, and polymorphism.


2 Answers

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:

  • Mootools Core
  • YUI
  • Prototype class inheritance

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

like image 111
naikus Avatar answered Oct 05 '22 13:10

naikus


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.

like image 37
Gabi Purcaru Avatar answered Oct 05 '22 13:10

Gabi Purcaru