2015-10-15 152 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