复制对象

      网摘 2006-4-20 10:14

摘自:http://www.darronschall.com/weblog/archives/000148.cfm

1.  the object is an instance of the class

function copyObject(obj) {
     // create a "new" object or array depending on the type of obj
     var copy = (obj instanceof Array) ? [] : {};
     
     // loop over all of the value in the object or the array to copy them
     for(var i in obj) {
         // assign a temporarity value for the data inside the object
         var item = obj[i];
          // check to see if the data is complex or primitive
         switch(item instanceof Array || item instanceof Object) {
             case true:
                // if the data inside of the complex type is still complex, we need to
               // break that down further, so call copyObject again on that complex
               // item
               copy[i] = copyObject(item);
                break;
            default:
               // the data inside is primitive, so just copy it (this is a value copy)
               copy[i] = item;
         }
     }
   return copy;
} 
/*
//Sample usage: 
var obj:Object = new Object();
obj.color = "red";
obj.count = 5;

// our second attempt at coping object
var obj2:Object = copyObject(obj);
obj2.color= "blue"

trace(obj.color);  // red
trace(obj2.color); // blue
*/
2. the object is not an instance of the class 
 
import mx.utils.ObjectCopy;

var dog1:Dog = new Dog("Yelowdog");

// use ObjectCopy to do the copy, and because we know the result
// is going to be a Dog, use the Dog cast so we don't get compiler errors
var dog2:Dog = Dog( ObjectCopy.copy(dog1) );
dog2.name = "Yellowdog Clone";

trace( dog1.speak() );	// Yelowdog says, 'Arf arf!'
trace( dog2.name ); 	// Yellowdog Clone
trace( dog2.speak() );	// Yellowdog Clone says, 'Arf arf!'
trace( dog2 instanceof Dog ); // true
 
 
 
 
*/
标签集:TAGS:
回复Comments() 点击Count()

回复Comments

{commentauthor}
{commentauthor}
{commenttime}
{commentnum}
{commentcontent}
作者:
{commentrecontent}