2015-10-15 194 views
0

在我SCSS腳本之一,我發現我不小心給一個@for循環計數器相同的名稱不同,全局變量,但如預期一切仍然工作。變量範圍的for循環

例如,粘貼示例腳本到http://sassmeister.com/

$w: white; 
$r: red; 
$b: blue; 
$y: yellow; 

//... 

$test: ''; 
//Accidentally using an existing variable name ($r) as the counter: 
@for $r from 1 through 10 { 
    @if($test != '') { $test: $test + ', '; } 
    $test: $test + $r; 
} 

.someclass { 
    /*Note: $r is 'red', not the @for counter. @for loops create their own scope?*/ 
    color: $r; 
    /*All the @for counters. @for created a *local* $r, but accessed the *global* $test...*/ 
    something: unquote($test); 
} 

...和CSS的樣子:

.someclass { 
    /*Note: $r is 'red', not the @for counter. @for loops create their own scope?*/ 
    color: red; 
    /*All the @for counters. @for created a *local* $r, but accessed the *global* $test...*/ 
    something: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10; 
} 

所以,我會認爲@for循環改變$rred10到它在.someclass中使用的時間,但(幸運的是)它沒有。這表示該循環在其自己的本地範圍內工作,但它仍然訪問全局變量$test,即使不使用!global標誌。

現在我很困惑。 docs指出mixin具有局部範圍,但我還沒有找到任何關於循環範圍的文檔。 這是「混合」範圍的文檔化功能 - 循​​環計數器是在一些本地範圍內,而循環「身體」在父範圍內工作 - 或者它是SCSS編譯器中的錯誤?

+0

你在這裏似乎沒有實際問題。唯一能回答「這是一個錯誤」的人是Sass的維護者。 – cimmanon

+0

@cimmanon - 好吧,你永遠不會知道。有些人比我更瞭解薩斯方式的內部運作(方式)。無論如何,我現在已經在他們的github頁面上提交了一個問題。 – Sphinxxx

回答

0

我不認爲這是編譯器中的錯誤,因爲我相信這是@for循環的預期行爲,但是您正確的是它不是documented。我會submit a request澄清/添加到官方文檔。

+0

感謝您的提示。我在github上爲此提交了一個問題。如果有人感興趣:https://github.com/sass/sass/issues/1863 – Sphinxxx

+1

答案:控制結構使用[「半全球」範圍](https://github.com/sass/sass/issues/ 1863#issuecomment-149702641)創建自己的局部變量,但仍可以訪問其他全局變量。 – Sphinxxx

+0

太棒了!感謝您的跟蹤 – kretzm