简体   繁体   English

在不使用全局变量的情况下从其他函数访问变量

[英]Accessing variables from other functions without using global variables

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. 我从各种各样的地方听说全局变量本质上是讨厌和邪恶的,但是当做一些非面向对象的Javascript时,我看不出如何避免它们。 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? 全局变量真的如此糟糕吗?

I think your best bet here may be to define a single global-scoped variable, and dumping your variables there: 我觉得这里最好的办法可能是定义一个全局范围的变量,并且有倾倒的变量:

var MyApp = {}; // Globally scoped object

function foo(){
    MyApp.color = 'green';
}

function bar(){
    alert(MyApp.color); // Alerts 'green'
} 

No one should yell at you for doing something like the above. 做上述事情的人不应该对你大喊大叫。

To make a variable calculated in function A visible in function B, you have three choices: 要使函数A中计算的变量在函数B中可见,您有三个选择:

  • make it a global, 使它成为一个全球的,
  • make it an object property, or 使它成为一个对象属性,或
  • pass it as a parameter when calling B from A. 从A调用B时将其作为参数传递

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);
}

Consider using namespaces: 考虑使用命名空间:

(function() {
    var local_var = 'foo';
    global_var = 'bar'; // this.global_var and window.global_var also work

    function local_function() {}
    global_function = function() {};
})();

Both local_function and global_function have access to all local and global variables. local_functionglobal_function都可以访问所有本地和全局变量。

Edit : Another common pattern: 编辑 :另一种常见模式:

var ns = (function() {
    // local stuff
    function foo() {}
    function bar() {}
    function baz() {} // this one stays invisible

    // stuff visible in namespace object
    return {
        foo : foo,
        bar : bar
    };
})();

The return ed properties can now be accessed via the namespace object, eg ns.foo , while still retaining access to local definitions. 现在可以通过命名空间对象(例如ns.foo访问return ed属性,同时仍保留对本地定义的访问权限。

What you're looking for is technically known as currying. 您正在寻找的是技术上称为currying。

function getMyCallback(randomValue)
{
    return function(otherParam)
    {
        return randomValue * otherParam //or whatever it is you are doing.
    }

}

var myCallback = getMyCallBack(getRand())

alert(myCallBack(1));
alert(myCallBack(2));

The above isn't exactly a curried function but it achieves the result of maintaining an existing value without adding variables to the global namespace or requiring some other object repository for it. 上面的内容并不完全是一个curried函数,但它实现了维护现有值的结果,而无需向全局命名空间添加变量或者需要一些其他对象存储库。

If another function needs to use a variable you pass it to the function as an argument. 如果另一个函数需要使用变量,则将其作为参数传递给函数。

Also global variables are not inherently nasty and evil. 全球变量本身也不是恶劣的。 As long as they are used properly there is no problem with them. 只要它们使用得当,它们就没有问题。

Another approach is one that I picked up from a Douglas Crockford forum post( http://bytes.com/topic/javascript/answers/512361-array-objects ). 另一种方法是我从Douglas Crockford论坛帖子( http://bytes.com/topic/javascript/answers/512361-array-objects )中选择的方法。 Here it is... 这里是...

Douglas Crockford wrote: Douglas Crockford写道:

Jul 15 '06 06年7月15日

"If you want to retrieve objects by id, then you should use an object, not an array. Since functions are also objects, you could store the members in the function itself." “如果你想通过id检索对象,那么你应该使用一个对象,而不是一个数组。由于函数也是对象,你可以将成员存储在函数本身中。”

function objFacility(id, name, adr, city, state, zip) {

    return objFacility[id] = {

        id: id,
        name: name,
        adr: adr,
        city: city,
        state: state,
        zip: zip

    }
}

objFacility('wlevine', 'Levine', '23 Skid Row', 'Springfield', 'Il', 10010);

"The object can be obtained with" “可以用”获得对象“

objFacility.wlevine

The objects properties are now accessable from within any other function. 现在可以从任何其他函数中访问对象属性。

I found this to be extremely helpful in relation to the original question: 我发现这对原始问题非常有帮助:

Return the value you wish to use in functionOne, then call functionOne within functionTwo, then place the result into a fresh var and reference this new var within functionTwo. 返回你想在functionOne中使用的值,然后在functionTwo中调用functionOne,然后将结果放入一个新的var中,并在functionTwo中引用这个新的var。 This should enable you to use the var declared in functionOne, within functionTwo. 这应该使您能够在functionTwo中使用functionOne中声明的var。

function functionOne() {
  var variableThree = 3;
  return variableThree;
}

function functionTwo() {
  var variableOne = 1;
  var var3 = functionOne();

  var result = var3 - variableOne;

  console.log(variableOne);
  console.log(var3);
  console.log('functional result: ' + result);
}

functionTwo();

If there's a chance that you will reuse this code, then I would probably make the effort to go with an object-oriented perspective. 如果您有可能重用此代码,那么我可能会努力使用面向对象的视角。 Using the global namespace can be dangerous -- you run the risk of hard to find bugs due to variable names that get reused. 使用全局命名空间可能很危险 - 由于变量名称被重用,您将面临很难发现错误的风险。 Typically I start by using an object-oriented approach for anything more than a simple callback so that I don't have to do the re-write thing. 通常我首先使用面向对象的方法,而不仅仅是简单的回调,这样我就不必重写了。 Any time that you have a group of related functions in javascript, I think, it's a candidate for an object-oriented approach. 任何时候你在javascript中有一组相关的函数,我认为,它是面向对象方法的候选者。

You can completely control the execution of javascript functions (and pass variables between them) using custom jQuery events....I was told that this wasn't possible all over these forums, but I got something working that does exactly that (even using an ajax call). 你可以使用自定义的jQuery事件完全控制javascript函数的执行(并在它们之间传递变量)....有人告诉我这不可能在这些论坛上,但我有一些工作正是这样做(甚至使用ajax电话)。

Here's the answer (IMPORTANT: it's not the checked answer but rather the answer by me "Emile"): 这是答案(重要提示:这不是经过检查的答案,而是我的回答“Emile”):

How to get a variable returned across multiple functions - Javascript/jQuery 如何获取跨多个函数返回的变量 - Javascript / jQuery

I don't know specifics of your issue, but if the function needs the value then it can be a parameter passed through the call. 我不知道你的问题的具体细节,但如果函数需要值,那么它可以是通过调用传递的参数。

Globals are considered bad because globals state and multiple modifiers can create hard to follow code and strange errors. Globals被认为是错误的,因为全局状态和多个修饰符可能会导致难以遵循的代码和奇怪的错误。 To many actors fiddling with something can create chaos. 对许多摆弄东西的演员来说,可能会造成混乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM