0

我有一个自定义对象,其中包含一个数组(称为“子项”),其中将存储相同类型的对象,从而创建一棵树。
假设它看起来像这样:

function CustomObject(){
    if (this instanceof Topic) {
    this.text = "Test";
    this.children = [];
    } else
        return new CustomObject(); }

现在,我想向该对象添加一个“forAll”方法,该方法将以深度优先的方式在该树的所有元素上执行作为参数提供的另一个函数。最好的方法是什么?

4

1 回答 1

1

像这样的东西?

CustomObject.prototype.forAll = function(func) {
  // process this object first
  func(this);

  // then process children
  for (var i = 0; i < this.children.length; i++)
    this.children[i].forAll(func);
}
于 2011-02-09T03:09:59.193 回答