「コピー」関数を作成して、オブジェクトのプロトタイプに追加しようとしています。再帰的に型チェックを行い、プロパティを新しいオブジェクトに割り当ててから、オブジェクトを返すことを計画しました...しかし、問題があるようです。次のコード スニペットを参照してください。
Object.prototype.copy = function()
{
for (prop in this)
{
console.log(prop); //Logs copy (the function)!!!
}
}
x = {"a": 1};
y = x.copy();
コメントで指摘したように、この非常に奇妙な動作を見つけましたが、なぜこれが起こっているのですか? コピー機能はObject.prototype
、インスタンス化されたオブジェクト自体ではなく、 にある必要があります! どうすれば修正できますか?を設定するだけthis.copy = undefined
で、まだ に頼ることはできますObject.prototype.copy
か?
これは、要求された完全なコード サンプルです。
Object.prototype.copy = function()
{
var object = this; //The object we are copying.
var newObject = {}; //The object we will return.
//Cycle through the properties of the object we are creating, copy them recursively.
for (prop in object)
{
if (!Object.prototype.hasOwnProperty.call(this, prop) || object[prop] == null)
{
continue;
}
if (prop == "copy")
{
console.log("Well, blah."); //This never prints!
}
if (typeof(object[prop]) == "object" && !(object[prop] instanceof Array)) //If the object's property is another object...
{
newObject[prop] = object[prop].copy(); //Set the copy of it to the new object as well.
console.log("1 --- " + prop); //This prints copy - two times! That defies logic!
}
else if (typeof(object[prop]) == "object") //If it's an array...
{
newObject[prop] = object[prop].slice(); //Do it in a nicer fashion.
console.log("2 --- " + prop);
}
else //You're safe to copy it.
{
newObject[prop] = object[prop];
console.log("3 --- " + prop + " --- " + object[prop]);
}
}
return newObject;
}