Javascript OOP

Javascript does not have classes. It’s not an easy concept to grasp if you’re coming from OOP languages like Java, C++, C#, etc. Javascript works with objects.

var obj = {};

That’s an object.

Objects can be manipulated at any time, you can add properties, or functions (methods). = “Object1”;
obj.method = function() { alert(; }

Objects can also be created with the new operator, which is something that might ring a few bells for the Java, C++, etc. developers:

var person = new Person(“Alice”);

Person is a function like the following:

var Person = function(name) { = name;
this.showName = function() { alert(; }

We can create as many persons as we’d like with the method above. One drawback is that the function showName is created every time, even if it doesn’t change. Enter prototype.

Prototype is just an object that every javascript object gets a reference to. If a name (property, method) cannot be resolved in the object, the prototype is also searched. So to avoid the previously mentioned drawback, we can re-write Person like this:

var Person = function(name) { = name;

Person.prototype.showName = function() { alert(; }

You can add any methods like that and they all get inherited by every instance of Person you create with the new operator.


Leave a Reply

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

You are commenting using your 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: