Avatar of elepil

asked on 

Seeking expert opinions on Javascript data object class

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");


Open in new window

JavaScriptScripting Languages

Avatar of undefined
Last Comment

8/22/2022 - Mon