Given this code:
----------------------------------------------------
#!/usr/bin/perl -w
use strict;
$| = 1;
use JavaScript;
my $rt = JavaScript::Runtime->new();
my $cx = $rt->create_context();
sub get_js {
my $next = 1;
# Make a perl function
$cx->bind_function(perl_next => sub {
return $next++;
});
$cx->eval(q{
function makeClosure() {
var next = 1;
var js_next = function() {
return 1;
return next++;
}
return function() {
return perl_next() * js_next();
}
}
});
return $cx->call('makeClosure');
}
my $clos = get_js();
print "$clos\n";
for (1..10) {
print $clos->(), "\n";
}
----------------------------------------------------
The call to $clos->() returns undef. If the returned JS function is
modified to
return function() {
return perl_next() * next++;
}
each call returns nan. If modified to
return function() {
return perl_next();
}
it correctly returns 1..10.
It looks as if the context that should be captured (closed over) by
the returned JS function is being lost. Is this expected behaviour?
--
Andy Armstrong, hexten.net