Monday, July 20, 2009

Funny OO of Java Script

During my recent experiments with Java Script I learned how object orientation works in it. It has a very lightweight way of constructing and managing objects. It is confusing at first and many features we know and like such as visibility or interfaces are impossible to use have to be hacked. Below I stress the most important features of Java Script's OO approach.

Cloning as a way of creating a new object

In Java Script there is no class definition. New Object is a cloned version of an object called prototype. Example below shows how it works.

function Parent() {
this.property1 = "Parent property"
Parent.prototype.parent_method = function() {
return "Method defined in Parent"

Child.prototype = new Parent()

var child = new Child()

It is just a copy of the parent assigned to be a prototype for a child which then gets copied whenever you create a new Child object.

Objects are just dictionaries

Objects are just dictionaries and (almost) nothing more than that. You can add and remove properties and there is no explicit property or method hiding mechanism like public/private/... visibility declaration in Java. Ability to easily extend object dynamically happens to be useful in many cases. As an example let me use a service locator I found useful as a way to hide that I had to use global context ;)

// serviceLocator is an instance of a singleton design pattern
var serviceLocator = new function ServiceLocator() {}

serviceLocator.service1 = new Service1()
serviceLocator.anotherService = new AnotherService()

This openness of the object interface may be dangerous though so use if carefully!

Functions are objects

... and because of that may be used in an object (method) or global (function) context or both.

function MyObject() {}

MyObject.prototype.method = function() {
return 'Hello';

obj = new MyObject();
func = obj.method;


When used in object context the 'this' variable may be used so properties and other methods of the object may be accessed.

No comments:

Post a Comment