我正在尝试制作一个“复制”功能并将其添加到对象的原型中。我计划递归地进行类型检查并将属性分配给一个新对象,然后返回该对象......但是,似乎有一个问题,请看这段代码:
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;
}