Home  |  Linux  | Mysql  | PHP  | XML
From:Andy Armstrong Date:Sat Nov  4 13:40:34 2006
Subject:JS closures lose context
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


Navigate in group perl.javascript at sever nntp.perl.org
Previous Next




  
© No Copyright
You are free to use Anything
Site Maintained by PHP Developer
Powered By PHP Consultants