admin管理员组文章数量:1431412
Is it possible to access an inner variable from an external function like this example?
function a(f) {
var c = 'test';
f();
}
a(function() {
alert(c); //at this point, c should = "test"
});
Is it possible to access an inner variable from an external function like this example?
function a(f) {
var c = 'test';
f();
}
a(function() {
alert(c); //at this point, c should = "test"
});
Share
Improve this question
asked Nov 22, 2010 at 17:29
elevanceelevance
433 bronze badges
4 Answers
Reset to default 4No, that won't work. What matters is where (lexically) a function is defined, not where it's invoked.
When figuring out what (if anything) "c" refers to, the language looks in the local scope, then in the next scope out based on the definition of the function. Thus if that invocation of "a" took place in another function that did have its own local "c", then that value would be what the alert showed.
function b() {
var c = 'banana';
a(function() {
alert(c);
});
}
b(); // alert will show "banana"
No, this is not possible. The scope you declare your anonymous function in does not have access to this c
variable -- in fact, nothing but a
will ever has access to c
.
No this will not work because the variable c
is defined within the function and is not available outside of the function. One option though is to pass the variable c
into the function provided to a
function a(f) {
var c = 'test';
f(c);
}
a(function(c) {
alert(c); //at this point, c should = "test"
});
As others have said, this isn't possible. You can
1. Declare the c
variable outside of the scope of the function
2. Pass an argument to f
:
function a(f) { var c = { name: 'test' }; f(c) };
a(function(o) { alert(o.name) })
本文标签: scopeAccess inner variables from external functions in javascriptStack Overflow
版权声明:本文标题:scope - Access inner variables from external functions in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745558523a2663330.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论