JavaScript 类 : (instanceof this)

标签 javascript class object this instanceof

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

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/

相关文章:

javascript - 如何修复 data.map 而不是函数 api

javascript循环遍历数组并访问键: value

java - 在类中使用构造函数中的变量/数组

java - 检查两个不同的 ArrayLists 是否相等

c++ - 如何将对象存储在 Vector 中的对象中? (C++)

javascript - 获取未定义错误的 'Uncaught TypeError: Cannot read property ' 地理编码

PHP/JS ?网站 : We have lost connection

java - 同一类中的类似方法

objective-c - 在没有新初始化的情况下使用类中的数据

javascript - 我如何在meteorjs中返回包含函数的对象?