在eval反序列化后,Javascript原型未定义 [英] Javascript prototype undefined after eval deserialization

查看:65
本文介绍了在eval反序列化后,Javascript原型未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试反序列化JSON数据并更新每个对象的原型并继承一个公共函数。

Attempting to deserialize JSON data and update each object's prototype and inherit a common function.

但是,以下脚本抛出错误people [0] .getFullName不是一个功能。分配后对象的原型似乎未定义。

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>


推荐答案

原型 property是 constructors 的属性,而不是实例的属性。您要找的是 __ proto __

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

坏消息是在所有浏览器中都不起作用。它在Firefox和Safari中有效,但在IE中不起作用。另一种方法是使用构造函数来实例化您的数组。不幸的是你必须复制所有属性:

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

这篇关于在eval反序列化后,Javascript原型未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆