【问题标题】:Less: Is there a difference between @arguments and ellipsis (...)?减:@arguments 和省略号 (...) 之间有区别吗?
【发布时间】:2013-10-30 03:02:22
【问题描述】:

我只是想知道,因为它今天出现在我们的项目中。 实现mixin并使用@arguments或省略号捕获参数时似乎没有区别,在google上也找不到任何有用的东西所以我在这里问。

例子:

.transition(@arguments) {
    -webkit-transition: @arguments;
    -moz-transition: @arguments;
    transition: @arguments;
}

.transition(...) {
    -webkit-transition: @arguments;
    -moz-transition: @arguments;
    transition: @arguments;
}

用途:

.transition(left 0.3s ease, top 0.3s ease);

这两种实现有什么优势吗?

【问题讨论】:

    标签: parameters arguments less mixins ellipsis


    【解决方案1】:

    好像没什么区别

    实际上,您是否尝试编译您的代码? 这些是完全不同的 mixin:

    // this is a mixin definition with a variable number of arguments
    .a(...) {
        // here you use built-in @arguments variable
        a-value: @arguments;
    }
    
    // this is a mixin definition with a single argument
    .b(@arguments) {
        // here you use a variable you've just declared in mixin's argument list
        // (and it's not the built-in @arguments!)
        b-value: @arguments;
    }
    
    test {
        .a(1, 2, 3); // OK
        .b(1, 2, 3); // Error
    }
    

    或者换句话说:

    .a(@arguments) {
        a-value: @arguments;
    }
    

    等于:

    .a(@x) {
        @arguments: @x; // defines a new variable that overrides the built-in one
        a-value: @arguments;
    }
    

    还有另一种声明变量参数列表的方法:.mixin(@whatever...)。 基本上它与(...) 相同,但当您需要以下内容时它很有用:

    .c(@head, @tail...) {
        head: @head;
        tail: @tail;
    }
    
    test {
        .c(1, 2, 3, 4, 5)
    }
    

    【讨论】:

      【解决方案2】:

      这两者之间的唯一区别是transition(...) 接受任意数量的参数,而transition(@arguments) 只接受一个参数。

      @arguments(在 mixin body 中)包含所有传递的参数,并且不依赖于什么是原始 mixins 参数,只要其中一个不称为 arguments

      在您的情况下,第一个 mixin 不会编译,因为您指定了一个参数,但传递了两个。 要将逗号分隔的列表作为一个参数传递给 mixin,请使用分号 (;) 作为分隔符:

      .transition(left 0.3s ease, top 0.3s ease;);
      

      如果你只传递一个参数,你的两个 mixin 基本上做同样的事情。

      您可以阅读更多 in the docs - 向下滚动一点以到达“@arguments 变量”。

      【讨论】:

      • 这是我监督的,实际上在我们的 mixin 调用的末尾有一个分号。这样它就可以同时使用@arguments 和省略号...
      • 仍然必须将其他答案标记为解决方案,因为在技术上存在差异。
      • 当然。我一定是没能用正确的语言表达我的想法——我想说,只要一个论点通过,就没有区别。我已经编辑了我的答案以使其更清晰。
      猜你喜欢
      • 1970-01-01
      • 2011-06-04
      • 2015-09-16
      • 2012-02-16
      • 1970-01-01
      • 2020-09-09
      • 2019-06-28
      • 2023-04-02
      • 1970-01-01
      相关资源
      最近更新 更多