我想检查一个对象是否是当前类的实例 它在类外部工作正常,但如果我从类内部调用它,则会出现错误
class test {
check(obj) {
return (obj instanceof this) //error: this is not a function
}
}
const obj = new test()
console.log(obj instanceof test) //true
console.log(new test().check(obj)) //ERROR
解决:
方法#1:(作者: @CertainPerformance ) 我们不能使用:return obj instanceof this,
因为(this)是一个对象(即:obj instanceof OBJECT),
所以我们可以使用构造器对象:
return obj instanceof this.constructor
方法#2:(作者: @Matías Fidemraizer )
return Object.getPrototypeOf(this).isPrototypeOf () //using this->better
//or: className.prototype.isPrototypeOf (obj)
//if you know the class name and there is no intent to change it later
方法#3:(作者:@Thomas) 使函数“check”静态
static check(obj) {
// now `this` points to the right object, the class/object on which it is called,
return obj instanceof this;
}
最佳答案
具体错误信息为:
Uncaught TypeError: Right-hand side of 'instanceof' is not callable
上线
return (obj instanceof this)
这是有道理的 - instanceof
的右侧应该是一个类(或函数),例如 test
。不能调用不是函数的东西(例如对象),因此 <something> instanceof <someobject>
没有意义。
尝试引用对象的构造函数,它将指向类 ( test
):
return obj instanceof this.constructor
class test{
check(obj){
return obj instanceof this.constructor
}
}
obj=new test()
console.log(obj instanceof test) //true
console.log(new test().check(obj)) //ERROR
关于JavaScript 类 : (instanceof this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53203971/