我试图在 JavaScript 中克隆一个对象。我制作了自己的具有原型功能的“类”。
我的问题:当我克隆一个对象时,克隆无法访问/调用任何原型函数。
当我访问克隆的原型函数时出现错误:
clone.render 不是函数
你能告诉我如何克隆一个对象并保留它的原型函数吗
这个简单的 JSFiddle 演示了我得到的错误:http: //jsfiddle.net/VHEFb/1/
function cloneObject(obj)
{
// Handle the 3 simple types, and null or undefined
if (null == obj || "object" != typeof obj) return obj;
// Handle Date
if (obj instanceof Date) {
var copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
var copy = [];
for (var i = 0, len = obj.length; i < len; ++i) {
copy[i] = cloneObject(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
var copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = cloneObject(obj[attr]);
}
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
}
function MyObject(name)
{
this.name = name;
// I have arrays stored in this object also so a simple cloneNode(true) call wont copy those
// thus the need for the function cloneObject();
}
MyObject.prototype.render = function()
{
alert("Render executing: "+this.name);
}
var base = new MyObject("base");
var clone = cloneObject(base);
clone.name = "clone";
base.render();
clone.render(); // Error here: "clone.render is not a function"