假设我们有一个类似的类:

 function Parent() {
    this.pool = []
 }

 Parent.prototype.addChild = function(instance) {
    instance.id = this.pool.length + 1;
    this.pool.push(instance);

    return this;
 };

 Parent.prototype.removeChild = function(index) {
    this.pool.splice(index, 1);
 };

 function Child() {
      //something
 }


因此,我的意思是:

var task = new Parent(),
    child = new Child(),
    child2 = new Child(),
    child3 = new Child(),
    child4 = new Child();
task.addChild(child).addChild(child2).addChild(child3).addChild(child4);


如果我们在console.log task.pool中添加了这一点,它将显示并收集ID为1,2,3,4的对象。

因此,让我们删除3:

tasks.removeChild(2);


现在task.pool将显示集合,但是1,2,4。

如何通过引用创建ID,也就是说,如果我删除3,则4会变为3,因此我们保持数字顺序没有间隙?

最佳答案

如何通过引用创建ID,也就是说,如果我删除3,则4会变为3,因此我们保持数字顺序没有间隙?


为此,您可以:


进行更改,更新Child id后,在池中循环,或者
Child实例提供对池的引用,并让它们根据它们在池中的位置动态生成其id值(例如,使用getter函数)


id查找而言,#1效率更高。 #2可能不太容易实现错误(例如,在池上执行操作而忘记更新id值)。但这也会增加ChildParent之间的耦合,这通常不是一个好主意。

#1的实时示例:



var Parent = (function() { // To give us a private scope for utility funcs
  function Parent() {
    this.pool = []
  }

  Parent.prototype.addChild = function(instance) {
    instance.id = this.pool.length + 1;
    this.pool.push(instance);

    return this;
  };

  Parent.prototype.removeChild = function(index) {
    this.pool.splice(index, 1);
    fixupIds(this.pool);
  };

  function fixupIds(pool) {
    pool.forEach(function(instance, index) {
      instance.id = index + 1;
    });
  }

  return Parent;
})();

function Child() {
  //something
}

var task = new Parent(),
  child = new Child(),
  child2 = new Child(),
  child3 = new Child(),
  child4 = new Child();
task.addChild(child).addChild(child2).addChild(child3).addChild(child4);
snippet.log(JSON.stringify(task, null, 2));
task.removeChild(2);
snippet.log(JSON.stringify(task, null, 2));

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>





我没有做#2的现场示例。坦白说,我真的,真的不会那样做。 :-)但是,如果这样做,您将使用Object.definePropertyid上定义一个Child.prototype属性,该属性在池中向上查找子项(子项必须知道其池)。

10-04 16:26
查看更多