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).

obj.name = “Object1”;
obj.method = function() { alert(this.name); }
obj.method();

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) {
this.name = name;
this.showName = function() { alert(this.name); }
}

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) {
this.name = name;
};

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

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

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s


%d bloggers like this: