[英]Callback function cannot access variable within parent function's scope
In the below code, variable text
is not accessible in the findTextToDelete
function (it generates an error) 在下面的代码中,在findTextToDelete
函数中无法访问变量text
(它会生成错误)
array = ['a', 'b', 'removeThis', 'c']; removeText("removeThis"); function removeText(text) { array.splice(array.findIndex(findTextToDelete),1); } function findTextToDelete(element) { return element === text; }
I am able to get around this by creating a global variable 'globalText': 我可以通过创建全局变量'globalText'来解决此问题:
var globalText = ""; array = ['a', 'b', 'removeThis', 'c']; removeText("removeThis"); function removeText(text) { globalText = text; array.splice(array.findIndex(findTextToDelete),1); } function findTextToDelete(element) { return element === globalText; } console.log(array)
However I am trying to understand why the first method does not work. 但是,我试图理解为什么第一种方法不起作用。
It seems there must be a better way to do this. 看来必须有更好的方法来做到这一点。 Is there a way to pass 'text' into the callback function? 有没有办法将“文本”传递给回调函数?
Any help would be appreciated. 任何帮助,将不胜感激。
You could use a closure over text
for finding the element. 您可以对text
使用闭包来查找元素。
function removeText(text) { array.splice(array.findIndex(findTextToDelete(text)), 1); } function findTextToDelete(text) { return function (element) { return element === text; } } var array = ['a', 'b', 'removeThis', 'c']; removeText("removeThis"); console.log(array)
Yes, I think you are confused with closure . 是的,我认为您对封闭感到困惑。
Callback function doesn't have caller's scope. 回调函数没有调用者的作用域。 So you can't access the variable text
in findTextToDelete
. 因此,您无法在findTextToDelete
访问变量text
。
If you want to access the variable, pass it to the callback function as an argument. 如果要访问该变量,请将其作为参数传递给回调函数。
Locals defined in one function are only available to other functions that are defined within the first function. 在一个函数中定义的本地仅可用于在第一个函数中定义的其他函数。 The scope of locals defined in a function is limited to that function. 函数中定义的局部变量的范围限于该函数。 This is generally known as lexical scoping . 这通常称为词汇作用域 。 (Other languages have different rules, but lexical is common in imperative languages.) (其他语言有不同的规则,但是命令式语言中的词汇很常见。)
So you need to define a function inside removeText
to access text
. 因此,您需要在removeText
内定义一个函数来访问text
。
One way is to just use a function literal rather than a named function: 一种方法是仅使用函数文字而不是命名函数:
function removeText(text) {
globalText = text;
array.splice(array.findIndex(function (element) {
return element === globalText;
}, 1);
}
Another way is to forward the extra value: 另一种方法是转发额外的价值:
function removeText(text) {
globalText = text;
array.splice(array.findIndex(function (el) { returnfindTextToDelete(el, text); }, 1);
}
function findTextToDelete(element, text) {
return element === globalText;
}
(If you're not stuck with backward compatibility then arrow functions make both easier to write.) (如果您不向后兼容,那么使用箭头功能可以使两者更容易编写。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.