【问题标题】:Variable scope in Sass for loopsSass for 循环中的变量范围
【发布时间】:2015-10-16 12:18:55
【问题描述】:

在我的一个 SCSS 脚本中,我发现我不小心给了一个 @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 循环在 .someclass 中使用时将 $rred 更改为 10,但(幸运的是)它没有。这表明循环在其自己的本地范围内工作,但它仍然访问全局 $test 变量,即使没有使用 !global 标志。

现在我很困惑。 docs 声明 mixins 具有本地范围,但我还没有找到任何有关 for 循环范围的文档。 这个“混合”范围是文档化的特性——循环计数器在某个本地范围内,而循环“主体”在父范围内工作——还是 SCSS 编译器中的错误? p>

【问题讨论】:

  • 您在这里似乎没有实际问题。唯一能回答“这是一个 bug”的人是 Sass 的维护者。
  • @cimmanon - 好吧,你永远不知道。有些人比我更了解 Sass 方式(方式方式)的内部运作。无论如何,我现在已经在他们的 github 页面上提交了一个问题。

标签: css sass


【解决方案1】:

我不认为这是编译器中的错误,因为我认为这是 @for 循环的预期行为,但你是正确的,它不是 documented。我会 submit a request 澄清/添加到官方文档中。

【讨论】:

  • 感谢您的提示。我已经在 github 上为此提交了一个问题。如果有人感兴趣:github.com/sass/sass/issues/1863
  • 回答:控制结构使用"semi-global" scope,它创建自己的局部变量,但仍然可以访问其他全局变量。
  • 太棒了!感谢关注
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-27
  • 1970-01-01
  • 1970-01-01
  • 2012-06-12
相关资源
最近更新 更多