1

I'm really not sure if this is possible in Javascript. Here's my function:

var tree = function(name, callback) {
  if (this.name) {
    this.name.push(name)
    print(this.name)
  } else {
    this.name = []
  }
  callback()
}

I'd like to use it as follows and print out the hierarchy:

tree("john", function() {
  tree("geoff", function() {
    tree("peter", function() {
      tree("richard", function() {
      })
    })
  })
  tree("dave", function() {
  })
})

Here's the desired output:

// ['john']
// ['john', 'geoff']
// ['john', 'geoff', 'peter']
// ['john', 'geoff', 'peter', 'richard']
// ['john', 'dave']

but unfortunately I'm getting

// ['john', 'geoff', 'peter', 'richard', 'dave']

for the last function call. Is there a way to get the desired outcome?

Kind regards

Adam Groves

3
  • Are you trying to get the desired output by either not modifying the tree function or not modifying the way you are calling it? Commented Jan 15, 2010 at 23:13
  • 1
    Do you just care about the appearance of the printed output, or the resulting array structure? Also, with the absense of a new operator, you know that this refers to window, yes? Commented Jan 15, 2010 at 23:17
  • I'd be happy to modify the tree function but would rather not alter the way it is called. Sorry for the delayed reply - I'm in Europe. Commented Jan 16, 2010 at 7:45

2 Answers 2

2

The reason why the last line is printing all the names is because this.names is never removing the names that are being added to it. You're just appending names onto it. So when the function call is made

callback()  

with the value

function() {
  tree("richard", function() {
})  

this.names = ['john', 'geoff', 'peter'] and after the call this.names = ['john', 'geoff', 'peter', 'richard']. So now when you call

tree("dave", function() {
});

this.names is still ['john', 'geoff', 'peter', 'richard'].

Try the following instead, and notice I changed this.name to this.names to make is easier to read.

var tree = function(name, callback) {
  if (!this.names) {
    this.names = [];
  }
  this.names.push(name);
  print(this.names);
  callback();
  this.names.pop();
}  
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant! Just what I was after.
1

I'm not certain what callback does, but you should probably use apply() or call() when you invoke it.

callback.apply( this, arguments );

1 Comment

Callback is just the function 'tree' again being passed to itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.