开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜