【发布时间】:2018-11-08 08:32:15
【问题描述】:
我想检查一个对象是否是当前类的实例 它在课堂外工作正常,但如果我从课堂内调用它会出错
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) 使函数“检查”静态
static check(obj) {
// now `this` points to the right object, the class/object on which it is called,
return obj instanceof this;
}
【问题讨论】:
标签: javascript class object this instanceof