Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / JScript.NET

JavaScript Constructor With Configuration Object

5.00/5 (6 votes)
4 Apr 2013CPOL1 min read 26.3K  
Object constructor with another object instead of named variables.

Introduction

This tip shows you how to initialize a JavaScript object, without having named constructors, but with another object.

The Classic Way

Let's say we have a person object with a name and an age. We would need to create a constructor that takes the name and age as arguments.

JavaScript
var person=function(name, age)  {
    this.name=name;
    this.age=age;   
}
        
var john=new person("john", 20);

From experience, I've found that I often like to initialize an object by sending in another object that holds the configuration for the new instance.

This can be done by using arguments[0];.

The Code

JavaScript
var person=function()   {
    for(var prop in arguments[0])   {
        this[prop]=arguments[0][prop];   
    }
}

var john=new person({
    name: "john",
    age: 20
});

Now I can extend the object on the fly.

Prevent Object Extension

It's pretty cool that I could extend the object by sending in a function as one of the properties of the object that's being sent into the constructor. But sometimes, I don't want this to be possible. In that case, I declare all legal properties before I copy the configuration and then check if this has the property being sent in.

JavaScript
var person=function()   {
    this.name=null;
    this.age=null
    for(var prop in arguments[0])   {
        if(this.hasOwnProperty(prop))   {
            this[prop]=arguments[0][prop];   
        }
    }
}

Now it will no longer be possible to add properties that weren't declared.

An Example of Use

I find this trick most useful when serializing server data into a working object.

Let's assume we'd have this JSON result.

JavaScript
{
    "firstname": "John",
    "lastname": "Smith",
    "age": 36
}

And we'd have the following prototype;

JavaScript
var person=function()   {
    this.firstname=null;
    this.lastname=null;
    this.age=null;
    for(var prop in arguments[0])   {
        this[prop]=arguments[0][prop];   
    }
}
person.prototype.getFullName=function()
{
    return this.firstname + " " + this.lastname;
}

We can now easily create working instances of Person out of Ajax json requests.

JavaScript
var user=null;
$.ajax({
    url: "data.json",
    success: function(data) {
        //assuming the server has set content-type:application/json
        //jquery will serialize the json for you
        user=new Person(data);
        alert(user.getFullName());           
    }     
});

History

  • April-5-2013: Added Ajax serialize example

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)