2016-03-25 32 views
-2

Özel bir nesneyi javascript'te bir json dizesine dönüştürmeye çalışıyorum ancak döngüsel bir referans hatası almaya devam ediyorum. JSON.stringify'ı kullanmanın bir yolu var mı, yoksa dizeyi kendim oluşturmak zorunda mıyım? İşte Özel javascript nesnesini json'a dönüştürme

benim kodudur:

function configuration(comments, instances, connections) 
{ 
    this.comments = comments; 
    this.instances = instances; 
    this.connections = connections; 

    return this; 
} 

function instance(id, type) 
{ 
    this.id = id; 
    this.type = type; 

    return this; 
} 

function connection(from, to) 
{ 
    this.from = from; 
    this.to = to; 

    return this; 
} 

function from(id, property, index) 
{ 
    this.id = id; 
    this.property = property; 
    this.index = index; 

    return this; 
} 

function to(id, property, index) 
{ 
    this.id = id; 
    this.property = property; 
    this.index = index; 

    return this; 
} 


var comments = "this is a test comment"; 
var instances = []; 
var connections = []; 

connections.push(connection(from("34hvd","inputs", 0), to("dheb3", "outputs", 0))); 
instances.push(instance("34vd", "tee")); 
instances.push(instance("dheb2", "average")); 

var config = configuration(comments, instances, connections); 
JSON.stringify(config); 

Eğer ben bir yorum (dize), örnekler (örneğin dizisi nesneleri) içeren yapılandırma nesnesi stringify çalışıyor ve bağlantı bağlantıları (dizi am görebileceğiniz gibi nesneleri).

Bunu yapmanın daha iyi bir yolu varsa lütfen bana bildirin. Teşekkür ederiz

+1

öncelikle özel nesnelerden oluşturulan JSON nesnesi alt türlerini korumak etmediğini 'new' anahtar kelime – Hacketo

+0

Not ile, nesne örneklerini oluşturarak başlamalıdır çalışacaktır. Onu ayrıştırdığınızda düz nesneler alırsın. JSON, özel nesne türlerini temsil etmenin herhangi bir yolu yoktur. – Barmar

cevap

3

this işlevini çağırıyorsanız, this, window'a başvurursanız, dairesel referansı oluşturan şey budur.

Bu

connections.push(new connection(new from("34hvd","inputs", 0), new to("dheb3", "outputs", 0))); 
instances.push(new instance("34vd", "tee")); 
instances.push(new instance("dheb2", "average")); 

var config = new configuration(comments, instances, connections); 
console.log(config) 
+0

Çok teşekkür ederim. Bu çözüldü. Kötü soru için özür dilerim ... – Aaron

İlgili konular