从其他函数访问变量而不使用全局变量 [英] Accessing variables from other functions without using global variables
问题描述
如果最初产生的数字是一个局部变量,那么它将不能从那里访问。如果这些函数是对象方法,我可以将这个数字作为一个属性,但它们不是,看起来有点过于复杂,因此要改变整个程序结构来做到这一点。是一个全局变量真的很糟糕?
为了使函数A中计算出的变量在函数B中可见,您有三种选择:
$ b
- 使它成为一个全局的元素,
- 使它成为一个对象属性,或 当从A调用B时,
- 传递它作为参数。
如果程序非常小,那么全局变量不是那么糟糕。否则,我会考虑使用第三种方法:
$ p $ function A()
{
var rand_num = calculate_random_number ();
B(rand_num);
}
函数B(r)
{
use_rand_num(r);
}
I've heard from a variety of places that global variables are inherently nasty and evil, but when doing some non-object oriented Javascript, I can't see how to avoid them. Say I have a function which generates a number using a complex algorithm using random numbers and stuff, but I need to keep using that particular number in some other function which is a callback or something and so can't be part of the same function.
If the originally generated number is a local variable, it won't be accessible from, there. If the functions were object methods, I could make the number a property but they're not and it seems somewhat overcomplicated to change the whole program structure to do this. Is a global variable really so bad?
To make a variable calculated in function A visible in function B, you have three choices:
- make it a global,
- make it an object property, or
- pass it as a parameter when calling B from A.
If your program is fairly small then globals are not so bad. Otherwise I would consider using the third method:
function A()
{
var rand_num = calculate_random_number();
B(rand_num);
}
function B(r)
{
use_rand_num(r);
}
这篇关于从其他函数访问变量而不使用全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!