Creating reusable objects in JavaScript
I just saw this great article about the benefits of using object notation to encapsulate groups of related functions and related data into a self contained unit that can be easily dropped into a page. That's what I think of a a 'behavior object'. That is you really just have the one object that you're using to control some behaviors on the page. Many times this is a widget of some sort that you can drop in. A color picker, or fancy date picker, etc... (Yeah, I know that's not always the case, but just roll with it.) Sometimes you need what I think of as a 'data object'. Data objects represent a set of related data and many times you'll need several of them at a time. A behavior object may use data objects to keep track of things.
Imagine we want an object to represent a person in a web application. We'll track their name, email address, and web site link. We'll add getter and setter methods for those too just for demonstration, but for this simple example it's really overkill. (You may want to add them for data validation or formatting purposes.)
Anyway, enough jabbering, let's see some code, damn it!
A simple starting object (just the name to start with):
SimplePerson = function(name){ this.name = name; this.getName = function(){ return this.name; }; this.setName = function(name){ this.name = name; }; }
Creating and using instances of the object:
function testPerson(){ var p1 = new SimplePerson("Mr. Foo"); var p2 = new SimplePerson("Mr. Bar"); alert(p1.getName()); //"Mr. Foo" alert(p2.getName()); //"Mr. Bar" p1.setName("Mr. Smooth"); alert(p1.getName()); //"Mr. Smooth" alert(p2.getName()); //"Mr. Bar" }
That's it for the very simple example! It's pretty easy.
Here's what your code might look like if you want to track more fields and have a nice utility method to return their name wrapped in a link tag. I'll leave out the getters and setters on this one since they don't really do anything. If you could set the member variables to be private you might need them but there's still nothing stoping you from doing
p1.name = "Mr. Butinski"
So anyway, here's the new code.
Person = function(name,email,url){ this.name = name; this.email = email; this.url = url; this.getWrappedName = function(){ return "a href='"+url+"'"+name+"/a"; }; } function testPerson(){ var p1 = new Person("Mr. Green","N/A","http://www.rhythmandcode.com/"); alert(p1.getWrappedName()); }
And there you have it. I'm sure this is not new info to a lot of people but hopefully a few people will stumble across it and learn something.