Create object in JavaScript using named parameters

The following code should look familiar, we’re creating an object and assigning a property.

function Person(id) {
	var self = this;
	self.id = id;
}

var instance = new Person(1);

One challenge with this approach is that as you add properties remembering their order can become a mental task.

function Person(id, firstName, lastName, phoneNumber) {
	var self = this;
	self.id = id;
	self.firstName = firstName;
	self.lastName = lastName;
	self.phoneNumber = phoneNumber;
}

var instance = new Person(1, 'Bill', 'Gates', '212-555-1234');

An alternate approach to consider is to use jQuery’s extend function (or Underscore, AngularJS, etc) which enables passing named parameters.

function Person(data) {
	var self = this;
	$.extend(self, data);
}

var instance = new Person({
	id: 1,
	firstName: 'Bill',
	lastName: 'Gates',
	phoneNumber: '212-555-1234'
});

A nice by-product of this approach is that it makes it simple to serialize/de-serialize the object, for example to store it to Local Storage.

var jsonString = JSON.stringify(instance);
// write to storage
// ...
// read from storage
var instance = new Person(JSON.parse(jsonString));