javascript - 克隆 Javascript 对象及其类型

标签 javascript types clone

有很多关于克隆 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/

相关文章:

javascript - 无法识别 Mozilla Firefox 中的右键单击事件

clone - 封装聚合/组合

mysql - 复制表中的所有行并防止重复键

linux - 什么时候 clone() 和 fork 比 pthreads 更好?

javascript - 在嵌套的 Polymer 自定义元素中访问 JavaScript 方法

javascript - jQuery 插件 : how to pass element reference to callback function?

javascript - 如何在 Highcharts 中添加动态数据?

java - Java 中的数据类型及其表示

c# - 在 .NET 中,在运行时 : How to get the default value of a type from a Type object?

Haskell 数据类型范围