Object-Oriented JavaScript – Part I (Objects)

OOP is a style of programming that allows you to define or manipulate your data as objects with attributes and methods applied to those objects. These objects can include features such as polymorphism, inheritance, encapsulation, modularity and more. If you’ve never used object-oriented-programming(oop), this post does assume some knowledge of OOP methodologies, hopefully you can follow along.

Object-Oriented JavaScript is an interesting topic, since Javascript can be easily written and run in procedural form. OOP is intended to help maintain software quality and making use of reusable attributes and methods. JavaScript isn’t really an Object-Oriented language by default, but it is object based so we can utilize enough of the concepts to make our scripts work.

Objects

I’ve been mentioning objects can be manipulated, JavaScript is object based and some of the features objects can include. But what is an object? An object simply put is a collection of attributes such as object elements and object behaviors. These object elements can be described as variables, which we’ve all used in JavaScript and other programming languages before. The object behaviors are best known as methods inside the objects, also known as functions.

JavaScript comes with many built in objects that we as a programmer can utilize. For example, Array, Image, Date, Boolean, Math, and more.

[code="js""""""]Var names = new Array(3);
names[0] = "David";
names[1] = "Eugene";
names[2] = "Shawn"; [/code]

With this code we now have an array object called ‘names’ that contains an a set of of 3 values which are the names we’ve provided.

[code="js""""""]alert(names[2]);[/code]

Will display a pop up box with the name ‘Shawn’ when run in a web browser.

As stated above, we can create our own objects and use them in an Object-Oriented manner. First we will create an empty constructor function for our object. We should remember that a constructor must retain it’s state, so remember to return it as true.

[code="js""""""]function Person() {
	return true;
}[/code]

We can now instantiate this method as an object via JavaScript’s new operator. The new operator tells JavaScript to create this object using the properties inside the objects constructor. You will notice you did the same thing above for JavaScript’s built in object Array, which JavaScript provides the Array constructor as a built in function, whereas with Person() we are making our own constructor function.

[code="js""""""]Var user  = new Person();[/code]

We now have a new object called user. Let’s add an attribute to the Person() constructor.

[code="js""""""]function Person() {
	this.name = 'Shawn';
}[/code]

This gives the Person constructor a default value for it’s name attribute. If we wanted to display the objects name we would do this:

[code="js""""""]alert(user.name);[/code]

This would print out ‘Shawn’ in a pop up box. The this keyword refers to the object that the constructor or method is an owner of. We can go further and change this user objects name. Perhaps we would like to change it to ‘Erin’. We would set the user objects name attribute with a new string.

[code="js""""""""""""""""""]User.name = 'Erin';
alert(user.name);[/code]

Now the pop up box will display ‘Erin’. Below I have included a full example for your convenience.

[code="js""""""""""""""""""]function Person() {
	this.name = 'Shawn';
	return true;
}
Var user  = new Person();
alert(user.name); // displays Shawn.

user.name = 'Erin';
alert(user.name); // displays Erin.[/code]

Now that we’ve discussed some of the object’s attributes, we should discuss how an object can have methods. Using similar examples we’ve touched on above we can build an object method that will allow the object to set the name object in the Person() constructor.

We create a method called getName(). This method will work with the Person object to return the objects name attribute.

[code="js""""""""""""""""""]function getName() {
	return this.name;
}[/code]

Inside our constructor we will then attach the getName() method to our object like so:

[code="js""""""""""""""""""]
function Person() {
	this.name = 'Shawn';
	this.getName = getName;
	return true;
}[/code]

Now we can use the getName() method to return the name attribute in our object. We can use similar code to our prior objects example and instantiate a new Person object and run the getName() method with the user object to get the name of said object. We will also change the name attribute and run the same getName() method again to get the new result.

[code="js""""""""""""""""""]var user = new Person();

alert(user.getName());
user.name = 'Erin';
alert(user.getName());[/code]

The pop up box will now display ‘Shawn’ first and then the second consecutive pop up will display ‘Erin’ because we set the user user object’s name attribute.
Here is the full example for your convenience. Feel free to play around with your own examples and post the results.

[code="js""""""""""""""""""]function getName() {
	return this.name;
}
function Person() {
	this.name = 'Shawn';
	this.getName = getName;
	return true;
}

var user = new Person();

alert(user.getName());
user.name = 'Erin';
alert(user.getName());[/code]

This concludes part one of our series on Object Oriented JavaScript. We will be offering more of this series over the next few days.

Please share or bookmark this post!
  • email
  • DZone
  • Twitter
  • Digg
  • del.icio.us
  • Facebook
  • Reddit
  • Slashdot
  • Netvibes
  • Technorati
  • Google Bookmarks
  • Fark
  • HackerNews
  • Suggest to Techmeme via Twitter
  • Tumblr
  • Add to favorites
  • RSS
Article tags: , ,
Posted by Shawn | Comments (16)

16 Responses to “Object-Oriented JavaScript – Part I (Objects)”

  1. viralpatel says:

    Really useful article. You may be interested in reading a similar article:Object oriented programming in JavaScript

  2. Your getName method should be declared on the prototype, otherwise, you’re recreating the getName method/function for every instance of Person (not so efficient). With it declared on the prototype, you only have one instance regardless of how many instances of Person you have.

    Person.prototype = {
    getName: function() { return this.name; },
    anotherMethod: function () { /* func body */ },
    yetAnotherMethod: function() { /* func body */ }
    };

  3. qinglu008 says:

    hellow.can I translate this post to Chinese in my blog?

  4. Shawn says:

    @Cancel Bubble – I haven’t used JavaScript with prototype, I think I should read up on it a bit. Thanks!

    @qinglu008 – You may, but please give credit back to my blog.

    @viralpatel – that is a very good article, thanks for the heads up!

  5. Shitic says:

    good tutorial

  6. Tony Chung says:

    @CANCEL BUBBLE: I think Shawn did a good job of introducing the concept of OOP to those who understand procedural programming.

    How to declare an object.
    How to instantiate an object.
    Create a function that can be used as a method.
    How to attach the external function as a method of the object.

    This could go on to explain

    How to adeclare methods within an object using anonymous functions.
    [your use of prototype (which sadly never worked for me when modifying default object types)]
    How to pass values into and out of an object
    WTF is a callback anyway?
    etc…

    @SHAWN: I got here by following a retweet of an @alexpuig post. I look forward to more in the series.

    -Tony

  7. Shawn says:

    @Tony and @Shitic – Thanks for the kind words.

    I’ll get more of this series out real soon guys, been a busy couple days here.

  8. Think of the prototype object as the template upon which an object is based. Any properties/methods on that prototype are passed on to all instances of that class.

    So in your example, if you ended up with 50 instances of Person, each instance of Person will have *it’s own copy* of the getName() method. That’s wasteful as you really only need one instance of that method (since it does the same thing for every instance).

    Putting the getName() method on the prototype object, you only have one instance of that method, but it’s passed on to those 50 instances of Person. Much more efficient.

    There’s an awesome book called “Pro JavaScript Design Patterns” by Ross Harmes and Dustin Diaz I highly recommend. It’s really a great look at Object Oriented JavaScript. You can pick up a used copy on Amazon for probably $20-25.

  9. [...] Object-Oriented JavaScript – Part I (Objects). | Unemployed Developer (tags: javascript) [...]

  10. [...] komplexer geht es beim “Unemployed Developer” zur Sache. Wie entwickelt man Objekt-Orientiert mit JavaScript, der erste Teil gibt bereits gute Einblicke in das [...]

  11. [...] Object Oriented JavaScript postings(Object-Oriented JavaScript – Part II (encapsulation) & Object-Oriented JavaScript – Part I (Objects)) and expand on them using [...]

  12. [...] Object-Oriented JavaScript – Part I (Objects). | Unemployed Developer [...]

  13. [...] Object-Oriented JavaScript – Part I (Objects). | Unemployed Developer [...]

  14. [...] Object-Oriented JavaScript – Part I (Objects). | Unemployed Developer [...]

  15. [...] Object-Oriented JavaScript – Part I (Objects). | Unemployed Developer [...]

  16. Eliza Hasas says:

    Hi, I found this blog article while searching for help with JavaScript. I have recently changed browsers from Chrome to Microsoft Internet Explorer 5. Just recently I seem to have a issue with loading JavaScript. Every time I browse page that requires Javascript, my browser doesn’t load and I get a “runtime error javascript.JSException: Unknown name”. I cannot seem to find out how to fix it. Any help is greatly appreciated! Thanks

Leave a Reply