views:

43

answers:

2

Say I have some context where variables are set and a λ-function is called which uses them directly:

function outerContext(){
    ...
    var data = ...; // some data the script uses
    ...
    someObject.method = function(){
        data; // the variable is used here
        };
    ...
    }

I know that the dynamically created function has a snapshot of the context it was created in, so data variable is accessible there.

What are the dangers I may face with such an approach when I use this dynamically created method? Should I always give this data as an argument or is it ok?

+2  A: 

I can't really think of any "dangers" besides the possibility of causing a circular reference and thus a memory leak in case of DOM objects or such.

It works much like a private variable in a class.

Jani Hartikainen
+3  A: 

The inner function does not have access to a "snapshot", it has full access to the data variable.

function outer() {
    var data = 1;

    ...

    someObject.method = function () {
        data = 42;
    };

    someObject.method();
    // data == 42
}

(The real explanation being that when using data in the inner function, Javascript will try to figure out which scope data is in. It will traverse up the scope chain to find the place where the variable was created, and that's the variable that will be used.)

There's no "danger", this is one of the core competencies of Javascript. It's like an object method modifying an object's properties. Of course you need to take care what you want to do, do you really want to modify the variable or do you just want to use it locally?

For the "snapshot", you need to use a closure:

function outer() {
    var data = 1;

    ...

    someObject.method = (function (data) {
        return function () {
            data = 42;
        }
    })(data);

    someObject.method();
    // data == 1
}
deceze
That's great, thank you!
o_O Tync