Skip to content Skip to sidebar Skip to footer

How To Map An Object Literal To Be An Instance Of My Constructor Function?

I have a constructor function like below: var Person = function (name, age) { this.name = name; this.age = age; } Person.prototype = { getAgePlusTwo: function () {

Solution 1:

If you can change the Person constructor to accept an object that keeps all the info instead of name and age params, I would do so:

FIDDLE http://jsfiddle.net/JPQ57/2/

JS

var Person = function (optns) {
    if(optns){
        this.name = optns.name || "";
        this.age = parseInt(optns.age) || 0;
    }
}

var json1 = {name: "Person2", age: "22"}

var p2 = new Person(json1);

Hope it helps


Solution 2:

If you don't want to modify the constructor you can create a factory function:

function makePerson(json){
  return new Person(json.name,json.age);
}

var p2 = makePerson({name:'Lebowski',age:41});
p2.getAgePlusTwo();

Fiddle here


Solution 3:

In a generic manner, try this :

function parseObject(jsonObject, classToRealize) {
    var isCorrect = true;
    var comparison = new classToRealize();
    var realizedObject = Object.create(classToRealize.prototype);

    if (Object.keys(jsonObject).length === Object.keys(comparison).length) {
        for (property in comparison) {
            if (typeof(comparison[property]) != 'function') {
                if(!jsonObject.hasOwnProperty(property)) {
                    isCorrect = false;
                    break;
                } else {
                  realizedObject[property] = jsonObject[property];  
                }
            }
        }
    } else {
        isCorrect = false;
    }

    if (isCorrect) 
        return realizedObject;
    else
        return null;
}

It'll check the json for integrity of the data, and allows you to parse any object from any json data. It'll return null in case of any error. I made a JSFiddle to illustrate it (it shows 4 alerts when you come to the page).


Post a Comment for "How To Map An Object Literal To Be An Instance Of My Constructor Function?"