Reputation: 58662
Relatively new to JavaScript, so wondering what is the best approach to achive the below requirement. I wanted to create JSON object (RPC request object), and need to enforce some structure. As I learn, JS is dynamic language hence I can add any type to an object at any time. But, I like to define a class, which I can populate to construct the JSON request.
var RecReq = {
ID:{},
HeaderLevel:{},
Content:{} //Content object goes here
},
HeaderLevel = {
HeaderID:{},
Note:{}
},
Content = {
Item: [] //Array of Item goes here
},
Item = {
IDs:[]
};
function ReceiveObj() {
this.RecReq = RecReq,
this.HeaderLevel = HeaderLevel,
this.Content = Content,
this.Item = Item
};
return new ReceiveObj();
I am sure many things wrong with the above code. I don't think the object is created with the arrays initialized.
On the returned object, I cannot do push()
operation to insert an iten onto Content.
How would you approach this. Do you create an object on the fly, or better to define an object which enforces some structure.
Upvotes: 1
Views: 411
Reputation: 34556
If, as your code suggests, you want your instances to inherit the outer object, one approach would be to assign the prototype of the 'class' (be careful of thinking in class terms in JS - it's not a class in the Java etc sense) to the object.
var obj = {
prop_1: 'foo',
prop_1: 'bar'
}
function Something() {
alert(this.prop_1); //alerts "foo"
}
Something.prototype = obj;
var something = new Something();
This is just one way. There are many patterns for controlling inheritance (and other patterns that would achieve what you want without even going near the concept of inheritance).
As for push()
not working, in your code, Content
is an object, whereas push()
is a method of the Array
prototype. In other words, you can push()
into an array only. Perhaps you meant Content.Item
, which IS an array.
Lastly, I would avoid capitalising names. In JavaScript, this tends to be done only with functions that are used in class simulation (like your ReceiveObj), to denote that they should be instantiated, not merely invoked.
Upvotes: 1