admin管理员组文章数量:1296331
I am creating an object in javascript. However, I know that I am using the new className() operator. I want to know if I can make a copy constructor so when I create a new object ie var object1 = object2, only the member variables in object2 are copied into object1, and not the pointer. Thanks!
I am creating an object in javascript. However, I know that I am using the new className() operator. I want to know if I can make a copy constructor so when I create a new object ie var object1 = object2, only the member variables in object2 are copied into object1, and not the pointer. Thanks!
Share Improve this question asked May 8, 2015 at 15:08 ExtremelySeriousChickenExtremelySeriousChicken 4182 gold badges5 silver badges16 bronze badges 3- Related: Most elegant way to clone a JavaScript object / What is the most efficient way to clone an object? – Jonathan Lonowski Commented May 8, 2015 at 15:10
- In the manner you described, no. For other options, use the search, this question has many duplicates. – Etheryte Commented May 8, 2015 at 15:10
- if members are objects do you want deep or shallow copy? – webduvet Commented May 8, 2015 at 15:21
1 Answer
Reset to default 7JS does not automatically generate constructors -- copy, move, or otherwise -- for any objects. You have to define them yourself.
The closest you'll e is something like Object.create
, which takes a prototype and an existing object to copy the properties.
To define a copy constructor, you can start with something along the lines of:
function Foo(other) {
if (other instanceof Foo) {
this.bar = other.bar;
} else {
this.bar = other;
}
}
var a = new Foo(3);
var b = new Foo(a);
document.getElementById('bar').textContent = b.bar;
<pre id="bar"></pre>
Using this to support deep copying is just a recursion of the same pattern:
function Foo(other) {
if (other instanceof Foo) {
this.bar = new Bar(other.bar);
} else {
this.bar = new Bar(other);
}
}
function Bar(other) {
if (other instanceof Bar) {
this.val = other.val;
} else {
this.val = other;
}
}
Bar.prototype.increment = function () {
this.val++;
}
Bar.prototype.fetch = function () {
return this.val;
}
var a = new Foo(3);
var b = new Foo(a);
a.bar.increment();
document.getElementById('a').textContent = a.bar.fetch();
document.getElementById('b').textContent = b.bar.fetch();
<pre id="a"></pre>
<pre id="b"></pre>
本文标签: Is there a copy constructor in JavascriptStack Overflow
版权声明:本文标题:Is there a copy constructor in Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741633735a2389516.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论