2014-01-26 1 views
0

저는 현재 JavaScript에 대한 이해를 깊게하고 있습니다. 특히 객체 상속과 관련하여 더욱 그렇습니다. 따라서 연습을 위해 API 클라이언트를 구현합니다. API는 상속이있는 JavaScript 객체 목록으로 변환하려는 객체 목록으로 구성된 JSON 객체를 반환합니다 (나중에 공통 객체를 Parent 객체에 추가 함).JSON에서 상속 된 JavaScript 객체를 얻는 방법은 무엇입니까?

저는 여기에 현재

json=JSON.parse('{"lista":[{"one":"","two":""},{"one":"","two":""}],"listb":[{"one":"","three":""},{"one":"","three":""}]}') 

function Parent(parent) { 
    this.one = parent.one; 
} 

function A(a) { 
    Parent.call(this,a); 
    this.two = a.two; 
} 

A.prototype = Object.create(Parent.prototype); 
A.prototype.constructor = A; 

function B(b) { 
    Parent.call(this,b); 
    this.three = b.three; 
} 

B.prototype = Object.create(Parent.prototype); 
B.prototype.constructor = B; 

function Collection(collection) { 
    this.lista = (typeof collection.lista !== "undefined" ? collection.lista.map(function (a) { 
     return new A(a) 
    }) : undefined); 
    this.listb = (typeof collection.listb !== "undefined" ? collection.listb.map(function (b) { 
     return new B(b) 
    }) : undefined); 
} 

collection=new Collection(json); 

자바 스크립트 JSON에서 상속 개체를 만들 수있는 더 나은 방법이 있나요을 수행하는 작업에 최소한의 예입니다? 당신이 C++/C#/자바 세계 :)에서 오는처럼

답변

2

얀이 경우이

json=JSON.parse('{"lista":[{"one":"","two":""},{"one":"","two":""}],"listb":[{"one":"","three":""},{"one":"","three":""}]}', 
    function(k,v){ 
     if(k === "lista") return v.map(function(a){return new A(a);}); 
     if(k === "listb") return v.map(function(a){return new B(a);}); 
     return v; 
    }) 

receiver 함수 뭔가 JSON.parse 사용할 수 json 필드 listaA 객체들의 배열 인 경우에는 두 필드 목적 및 listbB 개체

+0

덕분 배열 , 나는 그것이해야한다고 생각했던 것처럼 많이 본다. –

1

이 보이는

당신이 그것에서 얻을 수있는 모든 복잡성의 한층 더 함께 없지만 자바 스크립트에서 상속, 당신이 그것을 쓴 방법을 수행 할 수 있습니다

진짜 이득.

종종 JavaScripters는 첫 번째 행에서와 같이 JSON 기반 입력을 사용하여 요소를 객체로 직접 사용하기 만합니다.

var collection={}; 
collection.lista = json.lista; 
collection.listb = json.listb; 

하지만 본질적으로 상속 코드는 괜찮습니다.

관련 문제