javascript - 为什么我们需要在 switch 语句中分支时对位字段执行按位与

标签 javascript typescript bitmask

我真的不明白为什么我们需要在下面的代码中通过 BindingFlags.Types 应用按位 AND:

switch (binding.flags & BindingFlags.Types) {
    case BindingFlags.TypeElementAttribute:
      setElementAttribute(view, binding, renderNode, binding.ns, name, value);
      break;
    case BindingFlags.TypeElementClass:
      setElementClass(view, renderNode, name, value);
      break;
    case BindingFlags.TypeElementStyle:
      setElementStyle(view, binding, renderNode, name, value);
      break;
    case BindingFlags.TypeProperty:
      const bindView = (def.flags & NodeFlags.ComponentView &&
                        binding.flags & BindingFlags.SyntheticHostProperty) ?
          elData.componentView :
          view;
      setElementProperty(bindView, binding, renderNode, name, value);
      break;
  }

这是 BindingFlags 定义:

export const enum BindingFlags {
  TypeElementAttribute = 1 << 0,
  TypeElementClass = 1 << 1,
  TypeElementStyle = 1 << 2,
  TypeProperty = 1 << 3,
  SyntheticProperty = 1 << 4,
  SyntheticHostProperty = 1 << 5,
  CatSyntheticProperty = SyntheticProperty | SyntheticHostProperty,

  // mutually exclusive values...
  Types = TypeElementAttribute | TypeElementClass | TypeElementStyle | TypeProperty
}

有人可以澄清一下吗?

最佳答案

I don't really understand why we need to apply logical AND by BindingFlags.Types in the code below:

这是一个按位 AND (&),而不是一个逻辑AND (&&)。

您需要它来过滤掉其他位(例如,SyntheticProperty)。 BindingFlags.Type 仅包含 TypeXYZ 位。

例如,如果 binding.flags 同时具有 SyntheticProperty (0b00010000) 和 TypeElementClass (0b00000010),则其值为 0b00010010。由于 switch 只需要匹配类型的标志,它使用 BindingFlags.Types (0b00001111) 和 & 来屏蔽非类型值。 0b00010010 & 0b00001111 是 0b0001000,所以它匹配 SyntheticProperty 的情况。

关于javascript - 为什么我们需要在 switch 语句中分支时对位字段执行按位与,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54942413/

相关文章:

javascript - 拉取与位掩码关联的数组值

python - 检查位掩码的特定位

javascript - Ajax 中多次执行只有一个警报

JavaScript 鼠标移动事件

javascript - John Resig 的简单类实例化和 "use strict"

javascript - 使用箭头函数时,开发工具中未定义 `this`

typescript - 关于 rxjs debounceTime 的困惑

php - javascript中参数的位掩码类型

javascript - flot.js 图表中的单点有问题

javascript - 期望函数在 Jest 中抛出异常