instanceof 正在接受一个字符串作为我的类型的实例 class Javascript

instanceof is accepting a string as an instance of my Type class Javascript

当类型为字符串时,下面的 if 语句计算结果为真,我似乎无法弄清楚原因。这是我的代码:

const validateType = (instanceDescription, type) => {
    if (!type instanceof Type) {
        throw new Error(`type property of ${instanceDescription} is not 
                         a (child) instance of class Type`);
    }
}

我看不出 class 中的问题,因为它真的很简单。看起来像这样。

class Type {
    constructor(key, multipliers) {
        this.multipliers = multipliers;
        this.key = key;
    }
}

instanceof 比较是否发生了我不知道的事情,或者我快要发疯了。我通过检查某个 属性 是否未定义来绕过它,它将用于字符串,但我宁愿选择更清晰的 instanceof 选项

由于operator precendence,括号在这里有所不同。 ! 的优先级高于 instanceof,因此如果没有括号,您的测试将询问 false 是否是 Type:

的实例

class Type {
  constructor(key, multipliers) {
      this.multipliers = multipliers;
      this.key = key;
  }
}

let t = "somestring"

if (!(t instanceof Type)) { // << note the parenthesis
  console.log("error")
}
if (!t instanceof Type) {  // << never fires
  console.log("no error")
}