我有一个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.
答案 0 :(得分:1)
在你的clone函数中,测试对象上的每个方法,看它是否等于对象构造函数原型上的相同方法。
if (obj[method] != obj.constructor.prototype[method])
clone[method] = obj[method];
答案 1 :(得分: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();
尝试一下,看看它是否适合你,仍然很难说出你在做什么。如果没有,解释原因,那么我可以更好地理解这个问题。