使 javascript 变量在不同的函数中可见
make javascript variable visible in different functions
我需要在某处声明变量 a
,并使用 javascript 技术使其对 f1
函数内部调用的 f2
函数可见。但是直接调用(在 f1
函数之外) f2
函数必须无法打印 a。
我不能使用评估。
我无法更改 f2 功能。
我可以随心所欲地更改 f1 函数。
这可能吗?
function f1(var_name){
f2();
}
function f2(){
console.log(a);
}
f1(); // must log value of the a
f2(); // must not be able to log a
为什么不使用另一个全局变量?
您定义一个全局变量 a
并在函数 f1 中声明一个新的全局变量 b = a
,调用将打印 b
全局变量的 f2 函数,设置 gobal 变量 b
再次为 NULL。
这样,b
将仅在 f1 函数期间定义,并且将具有全局 a
变量的值。
这种方法只有在 f2() 已经使用 "this" 时才有效:
(在这种情况下,不会添加 "this" 支持)。
function f1(var_name){
var scope = {a: var_name};
f2.call(scope);
}
function f2(){
console.log(this.a);
}
f1(123); // must log value of the a
f2(); // must not be able to log a
你也可以考虑函数重载。
小变通。
全局声明一个并设置为未定义。
在 f1 中的 f2 函数调用之前设置 a
的值。在 f2 调用
后将 a
设置为未定义
var a = undefined;
function f1(var_name){
a = 'this is a ';
f2();
a = undefined;
}
function f2(){
console.log(a);
}
我需要在某处声明变量 a
,并使用 javascript 技术使其对 f1
函数内部调用的 f2
函数可见。但是直接调用(在 f1
函数之外) f2
函数必须无法打印 a。
我不能使用评估。
我无法更改 f2 功能。
我可以随心所欲地更改 f1 函数。
这可能吗?
function f1(var_name){
f2();
}
function f2(){
console.log(a);
}
f1(); // must log value of the a
f2(); // must not be able to log a
为什么不使用另一个全局变量?
您定义一个全局变量 a
并在函数 f1 中声明一个新的全局变量 b = a
,调用将打印 b
全局变量的 f2 函数,设置 gobal 变量 b
再次为 NULL。
这样,b
将仅在 f1 函数期间定义,并且将具有全局 a
变量的值。
这种方法只有在 f2() 已经使用 "this" 时才有效: (在这种情况下,不会添加 "this" 支持)。
function f1(var_name){
var scope = {a: var_name};
f2.call(scope);
}
function f2(){
console.log(this.a);
}
f1(123); // must log value of the a
f2(); // must not be able to log a
你也可以考虑函数重载。
小变通。
全局声明一个并设置为未定义。
在 f1 中的 f2 函数调用之前设置 a
的值。在 f2 调用
a
设置为未定义
var a = undefined;
function f1(var_name){
a = 'this is a ';
f2();
a = undefined;
}
function f2(){
console.log(a);
}