Top.Mail.Ru
? ?
Javascript's Journal
 
[Most Recent Entries] [Calendar View] [Friends View]

Thursday, September 12th, 2002

Time Event
9:52p
Using "objects" in JavaScript
Gee, it's been quiet in here lately. Submitted for your perusal: oftentimes in JavaScript there are circumstances where it would be desirable to allow a function to return more than one value -- for instance, a customer's complete contact information, or, if you're into mathematics, both the real and imaginary parts of a complex number. While JavaScript isn't a completely object-oriented language, it's surprising how flexible it can be.

For instance, let's say you have a dialog box that requests a customer's first name, last name, and phone number. Traditionally, you'd have to wing it, concatenating all of the information into a string like "firstname|lastname|phonenumber" and worry about what happens if the user maliciously/stupidly puts the | character in into one of the text fields. A more elegant solution is to define a customer "object" in JavaScript:


function MyCustomer(sFirstName, sLastName, sPhoneNumber)
{
this.firstName = sFirstName;
this.lastName = sLastName;
this.phonenumber = sPhoneNumber;
return this;
}


You can see that there's one property for each of the fields we want to encapsulate; the strange thing to understand is, like HTML expando properties, by referring to a new property you're implicitly creating it. Once this is done, you can instantiate MyCustomer objects, tweak their properties, and pass them between functions:


oMySillyCustomer = new MyCustomer('Raven', 'Jones', '(123) 456-7890');
alert(oMySillyCustomer.firstName); // pops up an alert dialog saying 'Raven'
alert(parseInt(oMySillyCustomer.phonenumber));

function validateCustomerPhoneNumber(oCustomer)
{
// Do something with oCustomer.phonenumber ...
}

validateCustomerPhoneNumber(oMySillyCustomer);

// Or create customers based on the values of textboxes in a form element:

oAnotherCustomer = new MyCustomer
(
document.forms[0].FIRSTNAME.value,
document.forms[0].LASTNAME.value,
document.forms[0].PHONENUMBER.value
);


Hope this helps somebody. Enjoy !

<< Previous Day 2002/09/12
[Calendar]
Next Day >>
About LiveJournal.com
Image