How do I match an object literal as an instance of my constructor function?

I have a constructor function as shown below:

var Person = function (name, age) {
    this.name = name;
    this.age = age;
}

Person.prototype = {
    getAgePlusTwo: function () {
        return this.age + 2;
    }
}

I can create such an object and access instance methods:

var p1 = new Person('Person1', 22);
p1.getAgePlusTwo(); 

However, I get my objects from the JSON service, so I cannot use newto create objects. Is there a way to map an object literal like this:

var p2 = { name: 'Person2', age: 25 }

to be an instance Person, so I can use its instance methods like p2.getAgePlusTwo()?

+3
source share
4 answers

If you can change the constructor Personto accept an object that stores all the data instead of the parameters nameand age, I would do this:

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

,

+2

, , , Person p2,

Person.prototype.getAgePlusTwo.call(p2)

, p2 , getAgePlusTwo. , , p2. Function.prototype.call MDN

+1

, factory:

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

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

+1

:

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 checks json for data integrity and allows you to parse any object from any json data. It will return null in case of any error. I made a JSFiddle to illustrate it (it shows 4 warnings when you come to the page).

+1
source

All Articles