0

How do I construct a new instance of a defined object?

I have code similar to this but the this.User = new User(); it doesn't work.

(function () {

SomeApp = {

    User: {
        FirstName: '',
        LastName: ''

    },

    Users: [],

    init: function () {
        this.User.FirstName = 'Joe';
        this.User.LastName = 'Blogs';

        //add user to list
        var copiedUser = {};
        $.extend(copiedUser, this.User);
        this.Users.push(copiedUser);

        //create new user
        this.User = new User();
        this.User.FirstName = 'Jane';

        //add user to list
        var copiedUser = {};
        $.extend(copiedUser, this.User);
        this.Users.push(copiedUser);
    }
}

SomeApp.init();

})();
I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
MakkyNZ
  • 2,215
  • 5
  • 33
  • 53
  • 6
    I may kill somebody if I keep reading "JSON object"... – Denys Séguret Oct 11 '12 at 13:01
  • Look here - he had a similar problem http://stackoverflow.com/questions/191881/serializing-to-json-in-jquery – Miha Rekar Oct 11 '12 at 13:01
  • 6
    `JSON, or JavaScript Object Notation, is a text-based open standard designed for human-readable data interchange.` (c) [Wikipedia](http://en.wikipedia.org/wiki/JSON). So, it is a string, **not an object**. – VisioN Oct 11 '12 at 13:02
  • 1
    @VisioN, that's an oversimplification. It is a string that represents a serialized Javascript object, and can be put in a one-to-one correspondence. – jonvuri Oct 11 '12 at 13:04
  • 2
    @Kiyura Many parts of an object and many values aren't representable in JSON and a JSON string definitively isn't an object. Your "one-to-one correspondence" doesn't mean a lot in this context. – Denys Séguret Oct 11 '12 at 13:06
  • I didn't contradict either of those? "One-to-one correspondence" wasn't totally accurate in both directions, I concede, because there is not a JSON string for every possible Javascript object; I meant rather that there is a unique Javascript object for every JSON string. – jonvuri Oct 11 '12 at 13:06

1 Answers1

3

If you want to be able to create object using new, you may create a "constructor" :

function User() {
    this.FirstName = '';
    this.LastName = '';
}

Side note : I'd recommend you to follow best practices in naming variables. Please read this guide.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758