Object-Oriented Javascript: Object Structures – Part 1
Object-Oriented Javascript: Object Structures
It’s been a while since I’ve posted. I’ve been working on a new project that makes heavy use of Javascript so I’ve been doing a lot of reading about object-oriented Javascript, since I prefer to use objects.
I was kind of surprised to note that there are tons of sites that talk about creating objects, but nearly all of them only show one method. In reality, there are many different structures you can use to define your Javascript. They are all very similar, but have subtle (though potentially very significant) differences.
Objects in Javascript
Javascript is not an object-oriented language like C++ or Java, though most things within Javascript are objects. You can create the Object definitions a number of ways (which we’ll be discussing in this article), but you create them all like this:
var myVar = new MyObject();
Prototyping
Out of all the methods, this one seems the most common. This method makes use of the ‘prototype’ object which all Objects contain. Basically, anything assigned to the prototype of an Object is created for all Objects.
The structure looks like this:
function MyObject() {
// constructor code goes here.
}
// Public properties:
MyObject.prototype.MyVar = 10;
// Public methods:
MyObject.prototype.MyFunction = function MyObjectFunction() {
// Code goes here.
}
Notice how I have a name on the function (function MyObjectFunction()). This name is mostly just so if you get an error, your Javascript console can tell you which function had the problem. The name can be just about anything. I usually use the same name for both sides, something like:
MyObject.prototype.MyFunction = function MyFunction() {
}
Inside of your functions you reference your variables by prefacing them with the ‘this’ keyword (so, if you wanted to refer to MyVar you would use this.MyVar).
Pros
- Enables inheritance (more on that in a bit)
- Only one instance of each function is made (saves memory)
Cons
- No private methods or properties
Encapsulation
This method puts all of your properties and methods into one function. This structure looks like this:
function MyObject {
// Private properties:
var myVar = 5;
// Private methods:
var myMethod = function myObjectMethod() {
// Code goes here.
}
return {
// Public properties:
X: 5,
// Public methods:
MyPublicMethod: function MyObjectPublicMethod() {
// Code goes here.
}
};
}
In your methods, you refer to your variables without ‘this’ or any other prefix.
Pros
- Allows for private properties and methods
Cons
- Creates duplicate functions (takes up more memory).
Now we’ve covered the two major structures for creating new objects. In the next part of this article we’ll talk about mixing and matching different aspects of these two structures to allow us to tailor the structures more to our needs.




