www.webdeveloper.com
Results 1 to 6 of 6

Thread: Is this a proper Javascript data model class?

  1. #1
    Join Date
    Feb 2014
    Posts
    12

    Is this a proper Javascript data model 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? Your critiques would be greatly appreciated.

    Here's the code:

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

    alert(person1.toString());
    alert(person2.toString());
    </script>

  2. #2
    Join Date
    Mar 2009
    Posts
    521
    This is the way I would do it if I wanted to create objects with private properties:

    Code:
    //create object with private properties using the "new" operator
    
    function Person(fn, ln){
        var x = {};  //create an object whose "name" only exists within the scope of this function
        x.fn = fn;
        x.ln = ln;
        x.setFirst = function(firstName){
    	x.fn = firstName;
        }
        x.setLast = function(lastName){
    	x.ln = lastName;
        }
        x.giveName = function(){
    	var str = x.fn + ' ' + x.ln;
    	console.log(str);
        }
        //attach it to the Person object like so
        this.setFirst = x.setFirst;
        this.setLast = x.setLast;
        this.giveName = x.giveName;
    }
    
    //use
    
    var a =new Person("John","Doe");
    
    a.giveName();  //prints John Doe
    a.setFirst("Henry");
    a.giveName();  //prints Henry Doe
    console.log(a.fn);  //undefined--the property that stores the first name can only be
    //accessed with getter/setter
    
    
    //=========================generating an object rather than using the "new" operator
    
    function makePerson(fn, ln){
        var x = {};  //create an object whose "name" only exists within the scope of this function
        x.fn = fn;
        x.ln = ln;
        x.setFirst = function(firstName){
    	x.fn = firstName;
        }
        x.setLast = function(lastName){
    	x.ln = lastName;
        }
        x.giveName = function(){
    	var str = x.fn + ' ' + x.ln;
    	console.log(str);
        }
        //difference from example above
        var y = {};
        y.setFirst = x.setFirst;
        y.setLast = x.setLast;
        y.giveName = x.giveName;
        return y;
    }
    
    //use
    var a = makePerson("John","Doe");
    //exhibits same behavior as object made with the new operator
    And I would not name a function "toString" although you can. It is the name of a method used with booleans in javascript.

  3. #3
    Join Date
    Feb 2014
    Posts
    12
    Thank you for responding, Tcobb.

    I understood the first half of your sample, but I have a question on the second half (i.e., your makePerson() function). I noticed you created a var y={} and defined your methods in that object. Doesn't that make both first and last names inaccessible from the outside? In other words, after you did:

    var a = makePerson("John", "Doe");

    How do you access the first and last names from your var a? Because console.log(a.giveName()) results in undefined.

    Your first half is very similar to my code sample, except you chose to put your fn and ln variables inside the object while I left mine outside.

    I do have a question, and I ask this because it is unclear to me. Can you explain to me the reason why you used the keyword 'new' to instantiate the first and not on the second? From what I see, both are functions, and apparently "new" is required on the first but not on the second, but I'm not sure why.

    Thanks.

  4. #4
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    255
    ...or you could do it like this:

    Code:
    function Add_person(fn, ln) {
             this.getName = function() {return fn + ' ' + ln};
             this.setName = function(x,y) {fn = x; ln = y}; 
          }
          
          var person = new Add_person("James","Bond");
          console.log(person.getName());
          person.setName("Pero","Peric");
          console.log(person.getName());

  5. #5
    Join Date
    Mar 2009
    Posts
    521
    How do you access the first and last names from your var a? Because console.log(a.giveName()) results in undefined.
    Actually if you write:

    Code:
    var a = makePerson("John","Doe");
    a.setFirst("Marvin");
    a.setLast("Brown");
    a.giveName();
    it does work.

    As to using the "new" operator, this allows you to use "prototype" on the Constructor and add properties/functions to any objects created, even after the fact. You can't do that if the object is created by the second method. Consider the following:

    Code:
    var a, b, c, d;
    a = new Person("Mike","Jones");
    b = new Person("Sue","Smith");
    c = new Person("Fred","Brown");
    //none of these objects have a method called "zap"--a.zap() will give an error
    Person.prototype.zap = function(){console.log("ZAP");};
    //now all of them have this even though they were created before 'prototype' added it.
    a.zap();
    b.zap();
    c.zap();
    //make a new one
    d = new Person("Pancho","Villa");
    d.zap();   //it zaps too
    There are various ways to create objects. Do whatever works for what you are trying to accomplish.

  6. #6
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,500
    Code:
    person = Object;
    
    newPerson = new person();
    newPerson.name = "Harry";
    alert( newPerson.name );
    outputs Harry to the dialogue.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles