Question about functions

Mar 13, 2011 at 1:01 AM

Hello -- please consider the following:

function id(x) { return x; }

var localtest = 'b';

globaltest = 'b';

the following all work

Enumerable.From(['a', 'b']).Select(id)

Enumerable.From(['a', 'b']).Select("$")

Enumerable.From(['a', 'b']).Select("a => a")

Enumerable.From(['a', 'b']).Select("$ == globaltest")

The following do not work

Enumerable.From(['a', 'b']).Select("id($)")

Enumerable.From(['a', 'b']).Select("a => id(a)")

Enumerable.From(['a', 'b']).Select("$ == localtest")

It appears that 'lambda expressions' inside quotes may not refer to external functions nor to local variable, but they may refer to external global variables. Is this correct? If so, I'm curious why. (This doesn't block me, I am just trying to understand linq.js a little better. I'm a big fan!)

Thanks.

Coordinator
Mar 13, 2011 at 8:41 AM

good question.

string expression use eval.
// new Function("$,$$,$$$,$$$$", "return " + expression)
The capturing scope is only global.
It is the specifications of the JavaScript.

If you want to capture local variable/method then use anonymous function.
for example

// local scope
window.onload = function ()
{
    var localValue = 100;

    // incollect
    Enumerable.From([10, 20]).Select("$ + localValue").WriteLine();

    // collect
    Enumerable.From([10, 20]).Select(function (x) { return x + localValue }).WriteLine();
}