Click here to Skip to main content
15,892,809 members
Articles / Programming Languages / Javascript
Tip/Trick

Introduction to JS Object Oriented Programming

Rate me:
Please Sign up or sign in to vote.
3.00/5 (1 vote)
2 May 2012CPOL2 min read 14.3K   3   2
The basics of OOP in JS.

Introduction

What is OOP?

Object Oriented Programming is a way to manage functions and variables without having to create like tons of functions with prefixes that you have to remember. In a logical way of explaining this, OOP supports data structures consisting of properties and methods, basically it's a way to group variables and functions. Since the Simula programming language, many dynamic programming languages have started to implement it too (e.g., C, C++); JS/EcmaScript is the first web-based programming language that supports OOP.

Classes

Image 1

You manage your functions and variables in classes. Just remember this, whenever I say "object", I mean class, Object is equivalent to Class. 

Creating our first object

1st way: Defining our object 

To create an object in JS, you do it almost like in Perl:

JavaScript
var my_obj = {};

Note that my_obj is the object's name.

These parentheses will contain our object's method & properties. 

Adding some methods and properties

Methods 

Methods are like functions, so you need to write an anonymous function inside the curly braces: 

JavaScript
someMethod: function(){ document.write("something"); } 

Note: someMethod is the Method's name 

You can also do: your object name + dot (.) + prototype + dot(.) = the property's name.

JavaScript
my_obj.prototype.someProperty = function(){ document.write("something"); };

Note that function() is not enclosed with the parentheses. 

Properties 

Properties are variables, to create it do this inside the curly braces:

JavaScript
someProperty: "someValue"

Note: someProperty is the property's name, someValue is the property's value

You can also do: your object name + dot (.) + prototype + dot(.) = the property's name as seen above.

JavaScript
my_obj.prototype.someProperty = "someValue"

Warning: When you're done with a method or a property in the parentheses, place a colon at the end of it if it's not the final method/property.

Constructors

Constructors are the second way to load an object with the developers arguments.

JavaScript
function me(sp,sm){
    this.someMethod=sm;
    this.someProperty =sp;
}

We're gonna make a duplicate the my_obj as seen above

JavaScript
var my_obj = new me("something", function(){ document.write("somemethod") } ) 

Initialize our object

We do not need to create an instance of our object. All we need to do now is access your object's methods/properties. Let's look at two examples using our object. 

Example 1 (Property):

To access a property, type in your object name + dot (.) + the property's name.

JavaScript
document.write(my_obj.someProperty);

Example 2 (Method):

To access a property, type in your object name + dot (.) + the property's name.

JavaScript
my_obj.someMethod(); 

Putting it together

Now that we have a complete object set-up, it's time to write the files! 

JS

JavaScript
var my_obj = {
    someMethod: function(){ document.write("something"); },
    someProperty: "someValue"
};

document.write(my_obj.someProperty + "<br>");
my_obj.someMethod();

JS (using constructors)

JavaScript
function me(sp,sm){
    this.someMethod=sm;
    this.someProperty =sp;
}

var my_obj = new me("something", function(){ document.write("somemethod") }

document.write(my_obj.someProperty + "<br>");
my_obj.someMethod();

HTML

XML
<script src='obj.js'></script>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Other
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 3 Pin
Priyank Bolia30-Apr-12 16:04
Priyank Bolia30-Apr-12 16:04 
QuestionMixing Methods... Pin
The_Mega_ZZTer30-Apr-12 10:04
The_Mega_ZZTer30-Apr-12 10:04 
I use OOP JS in my job and so I am familiar with these methods, however you are making the mistake of mixing two different methods. Also you do not explain in your article what exactly is going on.

There are two different ways to do OOP you are showing. The first, and the one I use at my job, involves prototype and the new keyword.

You probably want to create a constructor for any new classes, which you haven't done (you use a {} instead). If you make your class a function, that function will be called on construction with the "this" context set to the object being created.

So I do stuff like this:

JavaScript
function foo(uid) {
  this.uid = uid;
}

foo.prototype.incUID = function() {
  this.uid++;
}

var bar = new foo(1);
console.log(bar.uid); // Prints 1
bar.incUID();
console.log(bar.uid); // Prints 2


Alternatively:

JavaScript
function foo(uid) {
  this.uid = uid;
  this.incUID = function() {
    this.uid++;
  }
}

var bar = new foo(1);
console.log(bar.uid); // Prints 1
bar.incUID();
console.log(bar.uid); // Prints 2


But I would avoid doing it this way because class instances can't share functions (unless you have a really smart browser?) so you use more memory and creating the objects is slower due to the extra constructor code. Plus any of the hacks that add subclassing support to JS only work with prototype; they wouldn't know what to do with this because technically there is no class definition, it only occurs when the object is created and no sooner. So I'd recommend sticking to prototype.

The other method you were talking about looks like this:

JavaScript
var foo = {
  bar: function() {
    console.log(this.uid); // 1!
  },
  uid: 1
}

foo.bar();


This only creates one object so I recommend its use for namespaces rather than classes. You can even use both together to put classes in namespaces:

JavaScript
var Namespace = {
  ClassName: function() {
    // Constructor
  }
}

ClassName.prototype = {
  Func1: function() {
  },
  Etc: null
}


Not sure if all browsers are OK with completely overwriting prototype like that though (I don't use this method). So it's best to test first.

Oh yeah, the first method I showed works with every browser. Even IE6. We don't have to support that anymore, but it works.

Last tip:

JavaScript
inherit(SubClass, BaseClass); // Assume this function copies stuff from BaseClass's prototype to SubClass's... that's 50% of subclassing in JS right there...

function SubClass() {
}


This works even though you try to manipulate SubClass before its declared, due to JS's two-step parsing parsing functions before it runs any other code in the JS file. Or something like that. Makes for convenient syntax at least but it can be confusing.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.