Javascript prototype undefined after eval deserialization

eval, javascript, json, prototype

Solution

The `prototype` property is a property of constructors, not of instances. What you are looking for is the property `__proto__`:

people[i].__proto__ = new Person();

The bad news is that it does not work in all browsers. It does work in Firefox and Safari, it does not work in IE. An alternative is to use constructors to instantiate your array of people. Unfortunately you'll have to copy all properties:

function Person(obj) {
    for (var property in obj) {
        this[property] = obj[property];
    }
    return this;
}
Person.prototype.getFullName = function() {
    return this.firstName + ' ' + this.lastName;
}

var people;
eval('people = ' + json);
for(var i=0; i < people.length; i++) {
    people[i] = new Person(people[i]);
}

Problem

Attempting to deserialize JSON data and update each object's prototype and inherit a common function. However, the following script throws error "people[0].getFullName is not a function". The prototype for deserialized objects appears to be undefined after assignment. ``` <html> <head> <script> var json = '[ {"firstName": "John", "lastName": "Smith"}, {"firstName": "Nancy", "lastName": "Jones"} ]'; var people; eval('people = ' + json); function Person() { } Person.prototype.getFullName = function() { return this.firstName + ' ' + this.lastName; } //assign prototype for(var i=0; i < people.length; i++){ people[i].prototype = new Person(); } if(people[0].getFullName() !== 'John Smith') alert('Expected fullname to be John Smith but was ' + people[0].getFullName()); </script> </head> </html> ```

Original source