0

我有一个 javascript 对象克隆问题。我希望能够克隆已从对象原型定义的方法更改或在实例化后添加到对象的对象方法。这可能吗?

这里的设置是我定义的一个javascript“类”,所以我可以编写一个特定于我的对象类的克隆方法。我只是不知道如何复制方法。

例子:

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.
4

2 回答 2

1

在您的克隆函数中,测试对象上的每个方法,看看它是否等于对象的构造函数原型上的相同方法。

if (obj[method] != obj.constructor.prototype[method])
    clone[method] = obj[method];
于 2011-09-16T16:31:28.043 回答
0

听起来你只想要一个浅拷贝。但是要注意对象是在实例之间共享的,因为我们不是深度复制。

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

不同的语法是

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

尝试一下,看看它是否适合你,仍然很难说出你在做什么。如果没有,请解释原因,然后我可以更好地理解问题。

于 2011-09-16T19:12:25.630 回答