thanhhovn / sharpkit

Automatically exported from code.google.com/p/sharpkit
0 stars 0 forks source link

Closure variable capture #281

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
Variable capture doesn't follow the C# semantics. This is a simplified example 
from a larger set of code:

        [JsType(JsMode.Clr, Filename = "res/Default.js")]
        public class Node
        {
            public int Size { get; set; }

            public Func<int, int> DelayedFunction { get; set; }
        }

        static void btnTest_click(DOMEvent e)
        {
            new jQuery(HtmlContext.document.body).append("Hello world<br/>");

            var nodes = new List<Node>{new Node {Size = 10}, new Node { Size = 30}};

            SetupNodes(nodes);

            foreach (var node in nodes)
            {
                new jQuery(HtmlContext.document.body).append("Val: " + node.DelayedFunction(2).ToString());
            }
        }

        private static void SetupNodes(IEnumerable<Node> nodes)
        {
            //C# 5+
            foreach (var node in nodes)
            {
                node.DelayedFunction = multiplier => node.Size * multiplier;
            }
        }

This outputs 

Val: 60
Val: 60

whereas an equivalent console application correctly outputs

Val: 20
Val: 60

/*Generated by SharpKit 5 v5.00.5000*/

To match the C# semantics in JavaScript you need to hoist the relevant sections 
to function to C# scoping.

SharpKit generates quite confusing results as is to C# programmers (or most 
programmers used to sane lexical scoping!). If I wasn't experienced in writing 
JavaScript directly I'd be confused too! :-)

Original issue reported on code.google.com by co...@gravill.com on 15 Feb 2013 at 2:40