There are a lot of questions talking about cloning a JS
object, but it seems this one does not exist.
I have a function A
extending a function B
as follows:
function A () {}
function B () {}
B.prototype = new A()
I then have an object b
of type B
. I'd like to clone it, and preserve its type, so that the clone of b
would be of type B
.
Here is how I'm cloning it: (jsfiddle)
function A() {}
function B() {}
B.prototype = new A()
var b = new B()
var bPrime = new b.constructor()
$("#a").text(b instanceof A)
$("#b").text(b instanceof B)
$("#aPrime").text(bPrime instanceof A)
$("#bPrime").text(bPrime instanceof B)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
b is of type A: <span id="a"></span>
<br>b is of type B: <span id="b"></span>
<br>bPrime is of type A: <span id="aPrime"></span>
<br>bPrime is of type B: <span id="bPrime"></span>
In my example, the clone is of type A
. How could I have a clone of b that is typed B
?
You need to set
B.prototype.constructor
back toB
. As it is, it inherits fromA
, and the constructor isA
. So when you donew b.constructor()
, you're actually getting anew A()
.