简体   繁体   English

这是局部变量还是全局变量?

[英]Is this a local or global variable?

I am a beginner at using JS, right now I am working on a project, where I have to explain which global and local variables I have used, I am not sure which variables are global and which are local. 我是使用JS的初学者,现在我正在一个项目上,在这里我必须解释我使用了哪些全局变量和局部变量,我不确定哪些变量是全局变量,哪些是局部变量。 I know that a variable existing inside a function is a local variable, but I have the following: 我知道函数内部存在的变量是局部变量,但是我有以下几点:

onload=function(){
    var ctx=document.getElementById("canvas").getContext("2d");
};

Is my variable ctx inside the function? 我的变量ctx是否在函数内? I am not sure, since I've used onload , I don't know if ctx is a global or local variable? 我不确定,因为我使用过onload ,所以我不知道ctx是全局变量还是局部变量?

You are assigning a function to a variable (assigning to a variable makes no difference, it still creates the scope even if the function is not assigned), that gives ctx a functional scope. 您正在将函数分配给变量(分配给变量没有区别,即使未分配函数,它仍会创建作用域),这将为ctx提供功能作用域。 Anonymous functions are no different scope wise than a named function 匿名函数在范围上与命名函数没有不同

ctx在函数内部,这意味着它不是全局变量。

Note that it is declared inside of a function. 请注意,它是在函数内部声明的。 That means the scope of the variable is the function, which makes it local, correct. 这意味着变量的范围是函数,这使它成为局部的,正确的。 Look for where the var declaration is. 查找var声明在哪里。

Global variables are accessible from anywhere in the program, and have the same life cycle as the rest of the code. 全局变量可从程序中的任何位置访问,并且具有与代码其余部分相同的生命周期。 They are declared outside of any function scope. 它们在任何功能范围之外声明。

Any variable created inside a function is a local variable. 在函数内部创建的任何变量都是局部变量。 That mean it would only be present until you are inside the function ie While the function is being executed and won't be accessible from outside. 这意味着它只有在您位于函数内部时才存在,即在函数执行期间并且无法从外部访问。 And any variable declared outside a function is a global function as it can be easily accessed inside the function. 并且在函数外部声明的任何变量都是全局函数,因为可以在函数内部轻松访问它。 So in your case as your variable ctx has been declared inside a function hence it is local variable. 因此,在您的情况下,变量ctx已在函数内声明,因此它是局部变量。 Kindly see the link below for more detail on global variables 请查看下面的链接以获取有关全局变量的更多详细信息

http://snook.ca/archives/javascript/global_variable http://snook.ca/archives/javascript/global_variable

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

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