define local variable in some given scope
How could I define local variable in some given scope?
var f = function() {
// (1) var localVariable = 'some value';
alert(localVariable);
}
var defineLocalVariable = function(fnTarget) {
// (2开发者_高级运维) fnTarget['localVariable'] = 'blah...';
/* (3)
with (fnTarget) {
var localVariable = 'blah...'
} */
}
defineLocalVariable(f);
f();
Look at example. If uncomment (1) code will alert value of local variable of 'f' function 'some value'. What if I want to define this local variable programmatically in runtime, is it feasible? Could you propose implementation of 'defineLocalVariable' function to define local variable in 'f', something like (2) or (3) which are not working solutions.
Thanks.
Local variables are private ones. The concept of them is that they are inaccessible.
What you could do is passing it as an argument; that way, you can access it as a local variable. You should update f
's signature though.
var f = function(localVariable) {
alert(localVariable);
}
var defineLocalVariable = function(fnTarget) {
fnTarget(123);
}
defineLocalVariable(f);
but you cannot just set them for future use without calling (it seems like you want that).
Though, you could create another function that you can save, which passes a specific argument:
var f = function(localVariable) {
alert(localVariable);
}
var defineLocalVariable = function(fnTarget) {
return function() {
fnTarget(123);
}
}
var func = defineLocalVariable(f);
func();
but again, it does not modify the original function's scope directly.
精彩评论