javascript - 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;
}
解决方案
具体的错误信息是:
未捕获的类型错误:'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
推荐阅读
- r - 在条形图中向第三个变量添加另一个标签(ggplot2)
- unity3d - 如何生成一个随机数并确保在 Unity 中使用 Photon 的每个人都相同?
- mysql - sql中join语句如何执行
- android - Facebook 与来自 android 应用的元数据共享链接
- django - 从列表中向下移动后,Django url 无法工作
- c - 这个函数如何将我输入的单词数作为 argc 的参数?当你有一个未声明的 int 参数时总是这样吗?
- python - 从 git 推送和拉取后,我的 python exe (cx_freeze) 不起作用
- button - Indesign 按钮添加操作以在 acrobat 中打开查找窗口
- android - 如何使用 Android-Image-Cropper 制作位图
- xml - 通过 SOAP 在 Polarion 中创建工作项