![](/img/trans.png)
[英]What is the difference between @Scope (BeanDefinition.SCOPE_PROTOTYPE) and @Scope (“prototype”)?
[英]What is the difference between scope and block?
在書上看到一段代碼,如下:
x = 10;
if(x ==10) { // start new scope
int y = 20; // known only to this block
x = y * 2;
}
作用域和塊都一樣嗎?
作用域是您可以引用變量的地方。 一個塊定義了一個block scope
在一個block scope
定義的變量將僅在該塊內定義,並且您不能在塊結束后引用它。
所以在這段代碼中,如果你嘗試這樣的事情:
x = 10;
if(x ==10) { // start new scope
int y = 20; // known only to this block
x = y * 2;
}
y = 5; // error y is out of scope, not it is not defined
因為你在這里擁有的是一個本地范圍
java中的其他類型的范圍是class scope
(例如),類的成員具有類范圍,因此可以在類內的任何地方訪問它。
范圍的基本規則是:
當涉及條件和循環時,如果您不指定 {},則緊隨其后的語句是唯一屬於特定條件或循環的語句
例如
x = 10;
if(x ==10)
{
int y = 20;
x = y * 2;
}
both lines get executes only if condition returns TRUE
x = 10;
if(x ==10)
int y = 20;
x = y * 2; // this is not belong to if condition. therefore it will execute anyway
它們大多相同。
塊是一些被 { 和 } 包圍的代碼。 作用域是程序中某個事物可見的部分。 據我所知,所有塊都會創建作用域 - 塊中定義的任何內容在塊外都不可見。 反過來說是不對的。
以下是一些沒有塊的范圍:
for(int k = 0; k < 10; k++) { // k<10 and k++ are in a scope that includes k, but not in a block.
System.out.println(k); // this is in a block (the {})
}
for(int k = 0; k < 10; k++) // k<10 and k++ are in a scope that includes k, as above
System.out.println(k); // but there's no block!
class Test {
// this is a scope but not a block. Not entirely sure about this one.
int x = 2;
int y = x + 1; // I can access x here, but not outside the class, so the class must be a scope.
}
根據Block 的定義
塊是平衡大括號之間的一組零個或多個語句,可以在允許單個語句的任何地方使用。
所以
{ //block started
} //block ended
塊內聲明的變量是什么,范圍僅限於該塊。
這有道理嗎??
oracle 文檔將塊定義為
塊是平衡大括號之間的一組零個或多個語句,可以在允許單個語句的任何地方使用
@Mhd.Tahawi 已經說明了范圍是什么。
我應該指出的一件事,
switch(something){
case somethin1:
line1
line2
break;
case someting2:
line3
line4
break;
}
line{1,2,3,4} 在同一范圍內,因此阻塞,因為我沒有用大括號開始和結束每個案例。 與python不同,縮進並不意味着塊
Scope
是指visibility of variables
的visibility of variables
。 換句話說,程序的哪些部分可以看到或使用它。 通常,每個變量都有一個全局作用域。 一旦定義,程序的每個部分都可以訪問一個變量。
能夠將變量的范圍限制為單個function/block
非常有用。 該變量將具有有限的范圍。 這樣, function/block
內部的更改就不會以意想不到的方式影響主程序。
來自Mozilla 的 A re-introduction to JavaScript(JS 教程)
JavaScript 與其他語言(如 Java)之間的一個重要區別是,在 JavaScript 中,塊沒有作用域; 只有函數有作用域。 因此,如果變量是在復合語句中使用 var 定義的(例如在 if 控制結構中),則它對整個函數都是可見的。 但是,從 ECMAScript 2015 開始, let 和 const 聲明允許您創建塊范圍的變量。
給定 var 的示例以及它們與 int 和 const 的不同之處,我們可以得出結論,在 JavaScript 中,用 var 聲明的變量在其直接“范圍”之外是可見的,就像我們在其他語言中通常使用這個詞一樣。
在給定的示例中,在 for 循環中用 var 聲明的東西可以從函數中的任何地方使用,無論是在聲明它的 for 循環之前還是之后。
// myVarVariable *is* visible out here
for (var myVarVariable = 0; myVarVariable < 5; myVarVariable++) {
// myVarVariable is visible to the whole function
}
// myVarVariable *is* visible out here
這與使用 let 和 const 聲明的任何內容形成對比,后者僅限於聲明它們的塊,就像變量僅限於其他語言中一組花括號 { } 的直接范圍一樣。
這個故事的寓意是:如果您習慣了其他語言,請小心使用 var。 它比您預期的更強大和更明顯。
對於一般的編程語言來說,塊的作用域(也稱為塊作用域)只是作用域的一種; 參見https://en.wikipedia.org/wiki/Scope_(computer_science)#Levels_of_scope 。
一些語言,比如 Python,沒有塊也沒有塊作用域(而是有函數作用域、全局作用域等)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.