Answer the question
In order to leave comments, you need to log in
How to implement multilevel nested function launch?
I'm afraid that the title is fundamentally wrong is not entirely clear.
There are two classes of objects:
var record = function() {
var name;
this.name = name;
var value;
this.value = value;
}
var group = function() {
var _name;
this.name = _name;
var _status
this.status = _status;
var _stack = [];
this.stack = _stack;
}
var makeRecord = function(name,value) {
var newrecord = new record();
newrecord.name=name;
newrecord.value=value;
root.stack.push(newrecord);
}
var makeGroup = function(name,fun) {
var newgroup = new group();
newgroup.name=name;
var stack=[];
try{fun();} catch(e) {
newgroup.status=e;
}
newgroup.status='ok';
newgroup.stack=stack;
root.stack.push(newgroup);
}
makeRecord('first record','some text');
makeGroup('first group');
makeRecord('second record','yet another text');
makeGroup('second group',function(){
makeRecord('first record in second group','how can i do it?');
});
{
"name": "root",
"status": "ok",
"stack": [
{
"name": "first record",
"value": "some text"
},
{
"name": "first group",
"status": "ok",
"stack": []
},
{
"name": "second record",
"value": "yet another text"
},
{
"name": "first record in second group",
"value": "how can i do it?"
},
{
"name": "second group",
"status": "ok",
"stack": []
}
]
}
screenshot from chrome devconsole{
"name": "root",
"status": "ok",
"stack": [
{
"name": "first record",
"value": "some text"
},
{
"name": "first group",
"status": "ok",
"stack": []
},
{
"name": "second group",
"status": "ok",
"stack": [
{
"name": "first record in second group",
"value": "how can i do it?"
}
]
}
]
}
screenshot from chrome devconsoleAnswer the question
In order to leave comments, you need to log in
To do this, before calling the fun() function in makeGroup , the value of root must be temporarily replaced by the newly created group. Here is the new code for makeGroup:
var makeGroup = function(name,fun) {
var newgroup = new group();
newgroup.name=name;
newgroup.status='ok';
newgroup.stack=[];
var oldRoot = root;
root = newgroup;
try {
fun();
}
catch(e) {
newgroup.status=e;
}
root = oldRoot;
root.stack.push(newgroup);
}
I see the line in the source code:
root.stack.push(newrecord);
makeRecord
always adds a new entry to the root. parentGroup
tovar makeRecord = function(name,value, parentGroup) {
var newrecord = new record();
newrecord.name=name;
newrecord.value=value;
if(parentGroup === undefined) {
parentGroup = root;
}
parentGroup.stack.push(newrecord);
}
makeGroup
. makeRecord('first record','some text');
makeGroup('first group');
makeRecord('second record','yet another text');
makeGroup('second group', function(parentGroup) {
makeRecord('first record in second group','how can i do it?', parentGroup);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question