OO in Javascript

framework.graphics.object = function(id)
   this.name = "object";
   this.id = id;

That’s a “class”. To create an instance of that, you do the usual:

  var myObject = new framework.graphics.object(1);

In order to emulate an inheritance hierarchy, Javascript has this special property called prototype. You can set the prototype of an object to any other object. Object, not class. That’s a bit unusual from an OO perspective.
So it’s not proper OO, it’s an emulation of OO. It relies on the way the Javascript engine resolves properties and methods.
When you do: object.property1 or object.method1() Javascript looks in the object and sees if there is a local property and local method. If there isn’t one, it checks the prototype, then the prototype’s prototype until either the name is resolved or the chain ends.
It takes a bit of getting used to, but it’s still a very useful way of reusing code.


Tags: , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: