> > > It would be nice if we could clone layers :)

I would recommend doing it with a similar scheme as in java. Define an
"interface" cloneable, which contains a method called clone(). If an object
has an method called clone(), that will be run when cloning. Otherwise the
old object reference is kept.

The general solution which work for most of the objects looks something
like:

function clone() {
  var oNew = new Object();
  for (var i in this) {
    //If i is cloneable, clone it
    if (typeof(this[i]) == 'object' && this[i]['clone']!=null){
      oNew[i] = this[i].clone();
    }
    //Otherwise keep the old reference
    else{
      oNew[i] = this[i];
    }
  }
  return oNew;
}

I have not tested that code, but the idea should be clear. The previous code
has clearly a problem when cloning other than strictly hierarchical object
structures. If we try to clone an object which has an circular reference
(a.b == b && b.a == a), the result is not what we want. (A system crash,
namely) So we need to define individual clone methods for those complicated
objects.

Here is an example for something that imitates a twoway linked list:

function Node(left, right, content){
  this.left = left;
  this.right = right;
  this.content = content;
}

Node.prototype.clone = function(){
  var oNew = new Object();
  oNew.left = this.left; //Take the "old" reference, do not clone
  oNew.right = this.right.clone(); //clone this one
  if( typeof(this.content)=='object && this.content.clone!=null){
    oNew.content = this.content.clone(); //Clone it if its cloneable
  }
  else{
    oNew.content = this.content;
  }
}

This version of clone assumes that the clone is always started from the
leftmost node.

Note that you can still use the first method for the most of the objects, as
long as you remember to add the specific methods for the objects that need
them. You could even say that Object.prototype.clone = [the first method],
but then you need to take extra special care of the circular references.

This example here is not complete, but it should give a clear enogh picture
what needs to be done to provide means to clone objects.

--
Tuomas Huhtanen




_______________________________________________
Dynapi-Help mailing list
[EMAIL PROTECTED]
https://lists.sourceforge.net/lists/listinfo/dynapi-help

Reply via email to