Note that there are some explanatory texts on larger screens.

plurals
  1. POCloning JavaScript Objects. Again :(
    primarykey
    data
    text
    <p>I know it is really annoying to read this topic again. Before you start diggin into the code, one solution could be that I don't get prototypes and objects in JavaScript. But at this point i think, i do.</p> <p>The problem is:<br> <strong>How to clone an JavaScript Class (created with prototypes), so that the “cloned” Class remains untouched when extending and executing afterwards?</strong></p> <pre><code>function clone(obj){ if(obj == null || typeof(obj) != 'object') return obj; var temp = new obj.constructor(); for(var key in obj) temp[key] = clone(obj[key]); return temp; } var FOO = function() { var myBAR = clone(BAR); myBAR.prototype = jQuery.extend(true, myBAR.prototype, this); // deep cloning twice and extending with this console.log("FOO:", this.name); new myBAR(); }; FOO.prototype = { name: "FOO" }; var BAR = function() { console.log("BAR:", this.name); }; BAR.prototype = { name: "BAR" }; new FOO(); // returns FOO: FOO and BAR: FOO new BAR(); // returns BAR: FOO should return BAR: BAR </code></pre> <p>If i've got it right, the second call of <code>new BAR()</code> (after <code>new FOO()</code>) should return <code>BAR: BAR</code> not <code>BAR: FOO</code> as at the moment.</p> <p>One possible solution for this problem is an complete rewrite of the <code>clone</code> function in something like this:</p> <pre><code>function clone(obj) { return eval("("+obj.toString()+")"); // the same as eval(uneval(obj)); } </code></pre> <p>But this approach has an BIG downside, you can't pass any dynamically created objects.</p> <p>Any ideas?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload