數據透視表日期怎么選范圍
by Tiffany White
蒂芙尼·懷特(Tiffany White)
透視范圍 (Putting Scope in Perspective)
In JavaScript, lexical scope deals with where your variables are defined, and how they will be accessible — or not accessible — to the rest of your code.
在JavaScript中, 詞法作用域處理變量的定義位置以及其余代碼如何訪問(或不可訪問)它們。
There are two terms to think about when talking about scope: local and global. These two terms are important to understand, because one can be more dangerous than the other when declaring variables and executing your code.
在討論范圍時,要考慮兩個術語:本地和全局。 理解這兩個術語很重要,因為在聲明變量和執行代碼時,一個術語可能比另一個更為危險。
全球范圍 (Global Scope)
A variable is globally scoped if you declare it outside of all of your functions. For example:
如果在所有函數之外聲明變量,則該變量在全局范圍內。 例如:
//global variable, i.e. global scopevar a = "foo";
function myFunction() { var b = "bar"; console.log(a+b);}
myFunction();
When a variable is in the global scope, it can be accessed by all the code in the same JavaScript file. In this example, I’m accessing the variable a in my console.log statement, inside the myFunction function.
當變量在全局范圍內時,同一JavaScript文件中的所有代碼都可以訪問該變量。 在此示例中,我將在myFunction函數內的console.log語句中訪問變量a 。
當地范圍 (Local Scope)
Local variables only exist inside functions. They are scoped to that individual function.
局部變量僅存在于函數內部。 它們僅限于該單獨功能。
You can think of local variables as as any variables that fall between an opening and closing curly brace.
您可以將局部變量視為位于花括號之間的任何變量。
These local variables can’t be accessed by code outside of the function to which they belong.
這些局部變量不能由其所屬函數外部的代碼訪問。
Take a look at this code:
看一下這段代碼:
//global variable, i.e. global scopevar a = "foo";
function myFunction() { //local variable, or local scope var b = "bar"; console.log(a+b);}
function yourFunction() { var c = "JavaScript is fun!"; return c; console.log(c);}
myFunction();yourFunction();
Notice how the variables are each declared inside separate functions. They are both local variables, in local scope, and can’t be accessed by one other.
請注意,如何分別在單獨的函數中聲明變量。 它們都是局部變量,在局部范圍內,不能彼此訪問。
For instance, I can’t return b in yourFunction, because b belongs to myFunction. b can’t be accessed by yourFunction, and vice versa.
例如,我不能在yourFunction中返回b ,因為b屬于myFunction。 b無法通過yourFunction訪問,反之亦然。
If I were to try to return the value of b when calling yourFunction, I’d get “error: b is not defined.” Why? Because b doesn’t belong to yourFunction. b is outside of yourFunction’s scope.
如果在調用yourFunction時嘗試返回b的值, 則會收到“ 錯誤:b未定義。 為什么? 因為b不屬于yourFunction。 b在您的功能范圍之外。
When adding nested conditionals, scope gets even more hairy. But I’ll leave that for another time.
當添加嵌套條件時,作用域變得更加毛茸茸。 但我會再等一遍。
But for now, remember the difference between global scope and local scope. And the next time you get a “is not defined” error, check the variable’s scope.
但是現在,請記住全局范圍和本地范圍之間的區別。 下次您遇到“ 未定義 ”錯誤時,請檢查變量的范圍。
This post also appears at https://twhite96.github.io
這篇文章也出現在https://twhite96.github.io
翻譯自: https://www.freecodecamp.org/news/putting-scope-in-perspective-c9a16974c3be/
數據透視表日期怎么選范圍