当 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 选项
最佳答案
括号在这里有所不同,因为 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")
}
关于javascript - instanceof 接受一个字符串作为我的 Type 类 Javascript 的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52469701/