在下面的示例中,我可以调用tester1(1,2)并将“z”,“1”和“2”返回到控制台。
var labelTreeSorterClosureTest1 = function() {
var zVar = "z";
return function(a,b) { console.log(zVar), console.log(a), console.log(b) }
}
var tester1 = labelTreeSorterClosureTest1();
但是,如果我想使用我在别处定义的函数,如下所示:
function externallyDefinedFunction(a,b) {
console.log(zVar), console.log(a), console.log(b)
}
var labelTreeSorterClosureTest2 = function() {
var zVar = "z";
return externallyDefinedFunction;
}
var tester2 = labelTreeSorterClosureTest2();
如果我调用'tester2(1,2)',我会收到错误消息,说'z'未定义。我试图做一些没有意义的事情吗?
答案 0 :(得分:2)
您需要了解闭包的工作原理。调用方法时,上下文将切换到当前方法(与c#或java不同)以及与该函数相关的所有环境。因此,当它调用externallyDefinedFunction
(外部定义)时,不同于您在第一个实例中返回的匿名函数(由于定义函数的作用域而有权访问zVar)。,没有{{ 1}} defined.Make zVar
一个全局变量或解析错误或传递zVar引用或共享zVar使用此zVar
传递labelTreeSorterClosureTest2
内的实例externallyDefinedFunction
。
<强>更新强> 你能做这样的事吗?
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);
答案 1 :(得分: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();