Creating/populating Javascript custom object

Solution 1

You cannot access the first object's properties without instantiation, i.e. using the new keyword:

 var myUser = new User() ;
 document.write(myUser.id) ;

The second object is an object literal which is accessible without instantiation as it is already instantiated when parsed.

The difference comes into play if you want use prototypical inheritance to create a new object on basis of the old one. Writing an object literal is probably easier to understand and the more appropriate pattern if you have a rather compact code base. However, prototyping comes in handy if you want to create a new object by augmenting an existing object with another object without having to rewrite the object getting augmented:

ipUser.prototype = User ;
ipUser.ip =  "128.0.0.1" ;

In your case this difference might not seem striking, but you have to imagine how much redundant code you would get if you would create another object literal for every meager addition to the original object.

Look into the Mozilla Developer Center's page on JavaScript Objects if you have additional questions, it's outlined pretty well: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Object .

Hth

Solution 2

You don't have to create an object with empty values first. JavaScript doesn't need place holders and can add properties and methods dynamically at any time. That is, this would suffice as well:

var User2 = {};
User2.Id = 1;
User2.FirstName = 'John';
//...Etc.

If you're just concerned about storing data I'd use this form (the object literal, ie. your second method).

Update: You could also make things a bit easier and create a function that creates user objects for you:

function createUser(id, firstname, lastname, title) {
    return {
        Id: id,
        FirstName: firstname,
        LastName: lastname,
        Title: title
    };
}
var User2 = createUser(1, 'John', 'Smith', 'Manager');

Solution 3

The first is a typical object, known from OOP. You can add functions to act on the attributes like this (assuming there is a function getFullName):

var u = new User();
u.getFullName();

The second one is just an associative array, in which strings are mapped to values.

In JavaScript the boundary between the two is not as strict as in ohter programming languages.

Share:
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin 2 months

Related