我想检查一个对象是否是当前类的实例
它在类外部可以正常工作,但是如果我从类内部调用它就会出错
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)
我们不能使用:返回obj instanceof,
因为(this)是一个对象(即OBJECT的obj instance),
因此我们可以使用承包商对象:
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)
使功能“检查”为静态
static check(obj) {
// now `this` points to the right object, the class/object on which it is called,
return obj instanceof this;
}
最佳答案
具体的错误消息是:
未捕获的TypeError:“ instanceof”的右侧不可调用
在线上
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