有很多关于克隆 JS
对象的问题,但似乎这个对象不存在。
我有一个函数A
扩展了函数B
,如下所示:
function A () {}
function B () {}
B.prototype = new A()
然后我就有了一个 B
类型的对象 b
。我想克隆它,并保留它的类型,以便 b
的克隆将是 B
类型。
以下是我克隆它的方法:( 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>
在我的示例中,克隆的类型为A
。我怎样才能拥有一个输入为 B
的 b 克隆?
最佳答案
您需要将B.prototype.constructor
设置回B
。事实上,它继承自A
,构造函数是A
。因此,当您执行 new b.constructor()
时,您实际上得到了一个 new A()
。
function A() {}
function B() {}
B.prototype = new A()
B.prototype.constructor = B
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>
关于javascript - 克隆 Javascript 对象及其类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30712511/