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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: