troubleshooting Question

Seeking expert opinions on Javascript data object class

Avatar of elepil
elepil asked on
JavaScriptScripting Languages
3 Comments2 Solutions201 ViewsLast Modified:
My sample is a Person class with two properties -- first name and last name. What I have done does not resemble exactly as explained in any books I've read, but it somehow works for me because the two property variables, firstName and lastName, are private, and they can only be obtained and modified through their respective getters and setters methods.

I'm seeking opinions from you JavaScript experts out there whether you would do it this way as well. If not, why not? Please be forthcoming with your comments and critiques. Thanks.

Here's the code:

    var Person = function(firstName, lastName) {
        var firstName = firstName;
        var lastName = lastName;
        var obj = {
            getFirstName: function() {
                return firstName;
            setFirstName: function(name) {
                firstName = name;
            getLastName: function() {
                return lastName;
            setLastName: function(name) {
                lastName = name;
            toString: function() {
                return firstName + " " + lastName;
        return obj;
    // Now to use the class
    person1 = Person("John", "Doe");
    person2 = Person("Jane", "Down");

Join our community to see this answer!
Unlock 2 Answers and 3 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 3 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros