简体   繁体   English

如何访问 JavaScript 匿名函数中的变量

[英]How to access variable inside JavaScript anonymous function

How can I access variable C?如何访问变量 C?

test = function(){
    a = 1;
    b = 2;
    c = a+b;
    return c
}
console.log(c)

Returns:返回:

Uncaught ReferenceError: c is not defined

EDIT: Please disregard above question编辑:请无视上述问题

To elaborate more on this.更详细地说明这一点。 I am new to JavaScript and am stuck on a block of code that I can't get to work.我是 JavaScript 的新手,并且被困在我无法开始工作的代码块上。 I tried to simplify the problem I was having but I think that may have backfired...我试图简化我遇到的问题,但我认为这可能适得其反......

Here is the full code that I am having trouble with.这是我遇到问题的完整代码。 I need to access the variables inside of getAPIData.onload , But am getting "undefined" What is the best way to access these values?我需要访问getAPIData.onload内部的getAPIData.onload ,但我得到“未定义”访问这些值的最佳方法是什么?

getData();

function getData(){
  var activeMachines = [41, 44, 45]
  var dict = {};
  let data = activeMachines.reduce((obj, machineID) => {
    var getAPIData = new XMLHttpRequest();
    var url = 'http://127.0.0.1:8000/processes/apidata/' + machineID + '/';
    getAPIData.open('GET', url);
    getAPIData.send();
    getAPIData.onload = function(){
      var APIData = JSON.parse(getAPIData.responseText);
      dict['temp' + machineID] = APIData[0].tempData;
      dict['humid' + machineID] = APIData[0].humidData;
      timeValue = String((APIData[0].dateTime));
      dict['time' + machineID] = new Date(timeValue);
    }
    temp = dict['temp'+ machineID];
    humidity = dict['humid'+ machineID];
    time = dict['time'+ machineID];
    obj['machine_'+ machineID] = {temp, humidity, time}
    return obj
  }, {})
  console.log(data);
}

This returns the data dictionary, but all of the values are undefined.这将返回数据字典,但所有值都未定义。 Any help is appreciated.任何帮助表示赞赏。 I will read more into JavaScript scope as others have suggested.正如其他人所建议的那样,我将更多地阅读 JavaScript 范围。

c is a global variable that is created by calling the anonymous function assigned to the global variable test . c是一个全局变量,通过调用分配给全局变量test的匿名函数创建。 However, you never call the anonymous function assigned to test , therefore the variable never gets created.但是,您永远不会调用分配给test的匿名函数,因此永远不会创建该变量。

So, the obvious solution is to just call the anonymous function assigned to test :因此,显而易见的解决方案是调用分配给test的匿名函数:

test();

console.log(c);
// 3

However, this is a really bad idea.然而,这是一个非常糟糕的主意。 Global variables are evil, evil, evil.全局变量是邪恶的,邪恶的,邪恶的。 They tie together disparate parts of your program into a giant tangled mess: since they are accessible from everywhere, you have to assume that they may be accessed from everywhere.它们将您程序的不同部分联系在一起,形成一个巨大的混乱:因为它们可以从任何地方访问,您必须假设它们可以从任何地方访问。 And changing them in one place may change the behavior of some completely unrelated code in a completely different part of your code.在一个地方更改它们可能会在代码的完全不同部分更改一些完全不相关的代码的行为。

Actually, it is even worse: since they are global , changing them in one place may not only change the behavior of some completely unrelated code in a completely different part of your code, it may even change the behavior of some completely unrelated code in a completely separate part of someone else's code!事实上,它甚至更糟:因为它们是全球性的,改变他们在一个地方不仅可以改变你的代码的完全不同的部分的一些完全无关的代码的行为,它甚至可能改变在一些完全无关的代码的行为完全独立的其他人代码的一部分!

The only way to avoid this, would be to invent unique names for every global variable, otherwise they are going to clash.避免这种情况的唯一方法是为每个全局变量发明唯一的名称,否则它们会发生冲突。 In fact, you would need to invent a unique name for every global variable that was ever written, is written, and will be written by every programmer in the universe for all eternity!事实上,您需要为宇宙中所有程序员永远编写、编写和将编写的每个全局变量都发明一个唯一的名称!

But actually, there is no need for global variables here at all, since you actually return the value of c in your anonymous function.但实际上,这里根本不需要全局变量,因为您实际上在匿名函数中返回了c的值。 You can make those variables local to your function and simply use the return value.您可以将这些变量设置为函数的局部变量,并简单地使用返回值。 In fact, you don't even need variables at all, since you never "vary" them, you can make them constants instead.事实上,您甚至根本不需要变量,因为您从不“改变”它们,您可以将它们设为常量。

Note: in modern ECMAScript, you should always prefer const s (unless you have a very good reason to use a let ) and never use var or even worse (like you are doing here) implicit global variable definition.注意:在现代 ECMAScript 中,您应该始终更喜欢const (除非您有充分的理由使用let )并且永远不要使用var甚至更糟(就像您在这里所做的那样)隐式全局变量定义。 So, your code, in modern ECMAScript, should look like this:所以,你的代码,在现代 ECMAScript 中,应该是这样的:

const test = function () {
    const a = 1, 
        b = 2, 
        c = a + b;
    return c;
}

console.log(test());

Also, since you don't give your function a name and don't rely on dynamic scoping of this , you can use arrow function literal syntax:此外,由于您没有为函数命名并且不依赖this动态范围,您可以使用箭头函数文字语法:

const test = () => {
    const a = 1, 
        b = 2, 
        c = a + b;
    return c;
}

console.log(test());

or just give your function a name:或者只是给你的函数一个名字:

function test() {
    const a = 1, 
        b = 2, 
        c = a + b;
    return c;
}

console.log(test());

the variables AB and C are of use locally within the function, but it returns the value of C, with just calling the function returns the value, as it says - charlietfl console.log(test()) , you can call it that way or:变量 AB 和 C 在函数内本地使用,但它返回 C 的值,只需调用函数即可返回值,正如它所说 - charlietfl console.log(test()) ,你可以这样调用或者:

 var c = test ();
    alert(c) or console.log (c);

Now you can use the name varibale "c" outside the function.现在您可以在函数外使用名称变量“c”。

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

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