0

In this example below I could call tester1(1,2) and get "z", '1' and '2' returned to the console.

var labelTreeSorterClosureTest1 = function() {
    var zVar = "z";
    return function(a,b) { console.log(zVar), console.log(a), console.log(b) }
}
var tester1 = labelTreeSorterClosureTest1();

But what if I wanted to use a function I had defined elsewhere, such as follows:

function externallyDefinedFunction(a,b) {
    console.log(zVar), console.log(a), console.log(b)
}
var labelTreeSorterClosureTest2 = function() {
    var zVar = "z";
    return externallyDefinedFunction;
}
var tester2 = labelTreeSorterClosureTest2();

If I call 'tester2(1,2)' I get an error saying that 'z' is undefined. Am I attempting to do something that has no meaning?

4

2 回答 2

2

You need to understand how closures work. When a method is called, the context is switched to current method(unlike in c# or java) along with all the environment related to that function. So when it goes to invoke externallyDefinedFunction(which is externally defined) unlike the anonymous function that you return in first instance(which has access to zVar due to scope at which the function was defined)., there is no zVar defined.Make zVar a global variable or resolve the error or pass zVar reference or share zVar pass the instance labelTreeSorterClosureTest2 inside externallyDefinedFunction using this.

UPDATE can you do something like this ?

function externallyDefinedFunction(zVar, a,b) {
    console.log(zVar), console.log(a), console.log(b)
}


var labelTreeSorterClosureTest1 = function() {
    var zVar = "z";
    return function(a,b) { 
      externallyDefinedFunction(zVar, a, b); 
    }
}

var tester2 = labelTreeSorterClosureTest2();
tester2(1,2);
于 2013-10-10T15:25:16.587 回答
0
function externallyDefinedFunction(a,b) {
    // this variable is in the scope of the returned function
    var zVar = "in externallyDefinedFunction";
    console.log(zVar), console.log(a), console.log(b)
}
var labelTreeSorterClosureTest2 = function() {
    // this variable is private to the scope of labelTreeSorterClosureTest2
    var zVar = "i will never be seen!";
    return externallyDefinedFunction;
}
var tester2 = labelTreeSorterClosureTest2();
于 2013-10-10T15:27:12.093 回答