从其他函数访问变量而不使用全局变量 [英] Accessing variables from other functions without using global variables

查看:136
本文介绍了从其他函数访问变量而不使用全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从各种各样的地方听说全局变量本质上是讨厌和邪恶的,但是当做一些非面向对象的JavaScript时,我看不到如何避免它们。说我有一个函数,它使用一个使用随机数和东西的复杂算法来生成一个数字,但我需要在某个其他函数中继续使用该特定数字,这是一个回调函数,因此不能是同一个函数的一部分。

如果最初产生的数字是一个局部变量,那么它将不能从那里访问。如果这些函数是对象方法,我可以将这个数字作为一个属性,但它们不是,看起来有点过于复杂,因此要改变整个程序结构来做到这一点。是一个全局变量真的很糟糕?

解决方案

为了使函数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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆