首页 > 解决方案 > JavaScript 类:(this 的实例)

问题描述

我想检查一个对象是否是当前类的实例,它在类外部工作正常,但如果我从类内部调用它会出错

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,

因为(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;
  }

标签: javascriptclassobjectthisinstanceof

解决方案


具体的错误信息是:

未捕获的类型错误:'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


推荐阅读