Skip to content

Commit 76fa42f

Browse files
committed
Cloning objects.
1 parent 571ff00 commit 76fa42f

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/vm/js/nqp-runtime/sixmodel.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,17 @@ function STable(REPR, HOW) {
44
this.obj_constructor = function() {};
55
this.obj_constructor.prototype._STable = this;
66

7+
/* HACK - it's a bit hackish - think how correct it is */
8+
this.obj_constructor.prototype.$$clone = function() {
9+
var clone = new this._STable.obj_constructor();
10+
for (var i in this) {
11+
if (this.hasOwnProperty(i) && i != '_SC') {
12+
clone[i] = this[i];
13+
}
14+
}
15+
return clone;
16+
};
17+
718
/* Default boolification mode 5 */
819
this.obj_constructor.prototype.$$to_bool = function(ctx) {
920
return this.type_object_ ? 0 : 1;

t/nqp/94-clone.t

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
plan(5);
1+
plan(7);
22
sub foo() {
33
'hello there';
44
}
@@ -12,3 +12,21 @@ ok($b() eq 'hello there', 'you can call a cloned sub');
1212
nqp::setcodename($b, 'bumblebee');
1313
ok(nqp::getcodename($a) eq 'foo', "changing the name on the cloned sub doesn't affect orginal");
1414
ok(nqp::getcodename($b) eq 'bumblebee', "you can change the name on the cloned sub");
15+
16+
class Foo {
17+
has $!foo;
18+
method get_foo() {
19+
$!foo;
20+
}
21+
method set_foo($value) {
22+
$!foo := $value;
23+
}
24+
}
25+
26+
{
27+
my $c := Foo.new(foo => 123);
28+
my $d := nqp::clone($c);
29+
$c.set_foo(456);
30+
ok($d.get_foo == 123, "changing an attr on the cloned object doesn't affect the orginal");
31+
ok($c.get_foo == 456, "we can change an attr on the new object");
32+
}

0 commit comments

Comments
 (0)