instanceof正在接受字符串作为我的Type类Javascript

时间:2018-09-23 19:50:25

标签: javascript class instanceof

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

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

我看不到问题出在我的课堂上,因为它真的很简单。看起来像这样。

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

在我无法意识到的比较实例中是否发生了某些事情,或者我只是在发疯。我通过检查某个属性是否未定义来解决该问题,该属性将用于字符串,但我宁愿使用更清晰的instanceof选项

1 个答案:

答案 0 :(得分:2)

由于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")
}