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.