Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

JS closures lose context

1 view
Skip to first unread message

Andy Armstrong

unread,
Nov 4, 2006, 3:40:34 PM11/4/06
to perl-ja...@perl.org
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


Andy Armstrong

unread,
Nov 4, 2006, 3:46:16 PM11/4/06
to Andy Armstrong, perl-ja...@perl.org
On 4 Nov 2006, at 20:40, Andy Armstrong wrote:
> It looks as if the context that should be captured (closed over) by
> the returned JS function is being lost. Is this expected behaviour?

Oh and the 'return 1' in js_next was just me playing to find out
exactly what was being lost - but it doesn't affect the observed
behaviour.

--
Andy Armstrong, hexten.net

0 new messages