5

JSON データをデシリアライズし、各オブジェクトのプロトタイプを更新して、共通の関数を継承しようとしています。

ただし、次のスクリプトはエラー「people[0].getFullName is not a function」をスローします。逆シリアル化されたオブジェクトのプロトタイプは、割り当て後に未定義のように見えます。

<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>
4

4 に答える 4

4
于 2009-07-05T21:32:41.047 に答える
2
for(var i=0; i < people.length; i++){
      people[i].getFullName = Person.prototype.getFullName; }
于 2009-07-05T21:37:29.993 に答える
2

prototypeプロパティは、インスタンスではなくコンストラクタのプロパティです。あなたが探しているのはプロパティです:__proto__

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

悪いニュースは、すべてのブラウザーで機能するとは限らないことです。Firefox と Safari では動作しますが、IE では動作しません。別の方法は、コンストラクターを使用して人の配列をインスタンス化することです。残念ながら、すべてのプロパティをコピーする必要があります。

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]);
}
于 2009-07-05T21:34:08.657 に答える
2

基本的に、JSON オブジェクトを Person オブジェクトに取得する必要があり、その後 getFullName が適用されます。私はあなたが少し働かなければならなかったものを書き直しました。おそらくもっと良い方法がありますが、これがあなたが意図していたことだと思います...

<html>
<head>
<script>
//NOTE: Sending around JSON arrays leaves bad security holes for non-IE browsers (__defineSetter__)
var json = '[ {"firstName": "John", "lastName": "Smith"}, {"firstName": "Nancy", "lastName": "Jones"} ]';
//Persons is just a temporary JSON array
var persons = eval(json);

//constructor takes optional object instance and copies all properties if it gets one
function Person(person) { 
    if (person) {
        for(var prop in person)
        this[prop] = person[prop];
    }
}

//Prototype applies to all Person objects
Person.prototype.getFullName = function() {
    return this.firstName + ' ' + this.lastName;
}

//Create People array
var people = new Array();
for(var i=0; i < persons.length; i++){
    people[i] = new Person(persons[i]);
}

//Now do your check
if(people[0].getFullName() !== 'John Smith')
    alert('Expected fullname to be John Smith but was ' + people[0].getFullName());

</script>
</head>
</html>
于 2009-07-05T21:36:34.910 に答える