Object-Oriented JavaScript – Part III (jQuery)
I just wanted to write a simple and quick tutorial taking our initial Object Oriented JavaScript postings(Object-Oriented JavaScript – Part II (encapsulation) &
Object-Oriented JavaScript – Part I (Objects)) and expand on them using jQuery.
If you recall we had a Person object and a getName method inside of it. How would we do this in jQuery?
To run jQuery we need to get the latest library file from their website. Or you can connect to the library file on their code repository. But keep in mind if the code repository goes down while your site is up, your JavaScript will become broken. Best practices would be to download the latest library and host it on your server with the rest of your code. For these examples we will explain using the code repository link.
<script src="http://code.jquery.com/jquery-latest.js"></script>
Now that we are loading the latest jQuery library our next step is to actually start coding.
$(document).ready(function(){ });
We run the above command to check the document and wait until it’s ready to be manipulated. You can also do the above using other commands like:
$(function(){ });
I personally prefer the above way for no specific reason except its shorter.
So now we can add in our object and object instantiation.
var Person = {
firstname : 'Shawn',
lastname : 'Jones',
"getFirstName" : function() {
return this.firstname;
},
"getLastName" : function() {
return this.lastname;
},
"getFullName" : function() {
return this.firstname+" "+this.lastname;
}
};
$(document).ready(function(){
alert(Person.getFirstName ()); // Returns 'Shawn'
Person. firstname = 'Erin';
alert(Person.getFirstName ()); // Returns 'Erin'
alert(Person. getFullName ()); // Returns 'Erin Jones'
Person. lastname = 'Johnson';
alert(Person. getLastName ()); // Returns 'Johnson'
alert(Person. getFullName ()); // Returns 'Erin Johnson'
});
Of course as you can see I expanded on the prior examples to add new methods to the Person object. I hope as you step through this tutorial you can see how to apply the past JavaScript we did in jQuery. Not much different from the original examples is it? But at least this way you can start implementing some other jQuery methods and plugins into your OOP jQuery code. Read through the jQuery docs to find out more.
If you like this article, please use the buttons below to share it or leave me a comment and let me know your thoughts – Shawn








![Validate my RSS feed [Valid RSS]](http://www.unemployeddeveloper.com/wp-content/themes/ud2/images/valid-rss.png)
very cool & good tip, thank you very much for sharing.
Can I share this snippet on my JavaScript library?
Awaiting your response. Thank
It’s more of a demo snippet than anything but I guess you could put up there, just give credit back to here please.
Another very big WTF. There is object oriented and there is jquery – $?