简体   繁体   中英

How to write a javascript clone function that can copy added object methods?

I have a javascript object cloning question. I'd like to be able to clone object methods that have been altered from those defined by the object prototype, or added to the object after instantiation. Is this possible?

The setting here is a javascript 'class' defined by me, so I'm fine with writing a clone method specific to my object class. I just can't figure out how to copy methods.

Example:

function myObject( name, att, dif ) {
    /* 'privileged' methods */
    this.attribute = function(newAtt) {  // just a getter-setter for the 'private' att member
        if(newAtt) { att = newAtt; }
        return att;
    }
    // 'public' members
    this.printName = name;
}

myObject.prototype.genericMethod = function() {
    // does what is usually needed for myObjects
}


/* Create an instance of myObject */
var object153 = new myObject( '153rd Object', 'ABC', 2 );
// object153 needs to vary from most instances of myObject:
object153.genericMethod = function() {
    // new code here specific to myObject instance object153
}
/* These instances become a collection of objects which I will use subsets of later. */


/* Now I need to clone a subset of myObjects, including object153 */
var copyOfObject153 = object153.clone();
// I want copyOfObject153 to have a genericMethod method, and I want it to be the one
// defined to be specific to object153 above.  How do I do that in my clone() method?
// The method really needs to still be called 'genericMethod', too.

In your clone function, test each method on the object to see if it is equal to the same method on the object's constructor's prototype.

if (obj[method] != obj.constructor.prototype[method])
    clone[method] = obj[method];

It sounds like you just want a shallow copy. However beware of that objects are shared among instances since we're not deep copying.

function clone(obj) {
   var newObj = new obj.constructor();
   for (var prop in obj) {
     newObj[prop] = obj[prop];
   }
   return newObj;
}
var cloned = clone(object153);

A different syntax would be

myObj.prototype.clone = function() {
   var newObj = new this.constructor();
   for (var prop in this) {
     newObj[prop] = this[prop];
   }
   return newObj;
}
var cloned = object153.clone();

Try it out and see if it works for you, it's still hard to tell what you're doing. If it doesn't, explain why, then I can better understand the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM