Skip to content
On this page

自省 API

¥Introspection API

Stylus 支持内省 API。这允许 mixin 和函数相对于调用者进行反映,等等。

¥Stylus supports an introspection API. This allows mixins and functions to reflect relative to the caller, etc.

mixin

mixin 局部变量在函数体内自动分配。如果函数是在根级别调用的,则它包含字符串 root,否则包含 block,如果调用的函数需要返回值,则最后包含 false

¥The mixin local variable is automatically assigned within function bodies. It contains the string root if the function was called at the root level, or block indicating otherwise, and finally false if the invoked function expects a return value.

在下面的示例中,我们定义 reset() 来根据它是否混合到根、另一个块或返回值中来改变其行为,如下面的 foo 属性中所使用的:

¥In the following example, we define reset() to alter its behaviour depending on whether it's mixed into root, into another block, or into a return value, as used in the foo property below:

reset()
  if mixin == 'root'
    got
      root true
  else if mixin
    got 'a mixin'
  else
    'not a mixin'

reset()

body
  reset()
  foo reset()
reset()
  if mixin == 'root'
    got
      root true
  else if mixin
    got 'a mixin'
  else
    'not a mixin'

reset()

body
  reset()
  foo reset()

编译为:

¥Compiles to:

got {
  root: true;
}
body {
  foo: "not a mixin";
  got: "a mixin";
}
got {
  root: true;
}
body {
  foo: "not a mixin";
  got: "a mixin";
}