检查对象是否是类的“直接实例” [英] Check if object is a 'direct instance' of a class

查看:71
本文介绍了检查对象是否是类的“直接实例”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类:

class Bar extends Foo { // Foo isn't relevant
  constructor(value) {
    if (!(value instanceof Foo)) throw "InvalidArgumentException: (...)";
    super();
    this.value = value;
  }
}

class Baz extends Bar {
  constructor(value) {
    super(value);
  }
}

Bar 构造函数检查 value 是否是Foo的实例,如果不是,则会抛出错误。至少那是我想要的。如果您将 Bar Baz 作为值传递,则if语句返回 true 。目标是只让 Foo 通过。

我发现此答案已经,但是并没有真正回答我的问题。

The Bar constructor checks if value is an instance of Foo, it throws an error if it isn't. At least, that's what I wanted it to do. If you pass a Bar or a Baz as value, the if-statement returns true as well. The goal is to only let Foos through.
I found this answer already but that didn't really answer my question.

推荐答案

检查构造函数:

if (!value || value.constructor !== Foo)
  throw 'InvalidArgumentException: (...)';

或对象的原型(这与 instanceof 确实):

or the prototype of the object (this is more similar to what instanceof does):

if (!value || Object.getPrototypeOf(value) !== Foo.prototype)
  throw 'InvalidArgumentException: (...)';

这篇关于检查对象是否是类的“直接实例”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆