Javascript cloned object looses its prototype functions

Posted by Jake M on Stack Overflow See other posts from Stack Overflow or by Jake M
Published on 2012-04-14T05:13:37Z Indexed on 2012/04/14 5:28 UTC
Read the original article Hit count: 199

Filed under:

I am attempting to clone an object in Javascript. I have made my own 'class' that has prototype functions.

My Problem: When I clone an object, the clone cant access/call any prototype functions.

I get an error when I go to access a prototype function of the clone:

clone.render is not a function

Can you tell me how I can clone an object and keep its prototype functions

This simple JSFiddle demonstrates the error I get: 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"

© Stack Overflow or respective owner

Related posts about JavaScript